Creating & Reading
Create single- and multi-id errors, then read and narrow them by id.
Creating errors
Section titled “Creating errors”// Single id — context required per schemaconst err1 = err_auth.fromId("invalid_credentials", { username: "alice" });
// Multi-id in one error — several things went wrong at onceconst err2 = err_auth.fromContext({ invalid_credentials: { username: "bob" }, rate_limited: { retryAfter: 30 },});
// Chain additional ids after constructionconst err3 = err_auth.fromId("account_locked").addId("rate_limited");A single NiceError can carry multiple active ids. This models real situations — a request that is both unauthenticated and rate-limited — without forcing you to pick one.
Reading and narrowing
Section titled “Reading and narrowing”// Check and narrow — inside the guard, getContext is fully typedif (err1.hasId("invalid_credentials")) { const { username } = err1.getContext("invalid_credentials");}
// Check several ids at once — narrows to that subsetif (err2.hasOneOfIds(["invalid_credentials", "rate_limited"])) { // ...}
// All active idserr2.getIds(); // ["invalid_credentials", "rate_limited"]Pattern matching
Section titled “Pattern matching”matchFirst runs the first handler whose id is active and returns its result. Provide _ as a fallback.
import { matchFirst } from "@nice-code/error";
const message = matchFirst(err1, { invalid_credentials: ({ username }) => `Wrong password for ${username}`, account_locked: () => "Account locked", _: () => "Unknown auth error",});Instance properties
Section titled “Instance properties”const e = err_auth.fromId("invalid_credentials", { username: "alice" });
e.domain; // "err_auth"e.message; // "Invalid credentials for: alice"e.httpStatusCode; // 401e.getIds(); // ["invalid_credentials"]Next: Domain hierarchies →