Skip to content

Creating & Reading

Create single- and multi-id errors, then read and narrow them by id.

// Single id — context required per schema
const err1 = err_auth.fromId("invalid_credentials", { username: "alice" });
// Multi-id in one error — several things went wrong at once
const err2 = err_auth.fromContext({
invalid_credentials: { username: "bob" },
rate_limited: { retryAfter: 30 },
});
// Chain additional ids after construction
const 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.

// Check and narrow — inside the guard, getContext is fully typed
if (err1.hasId("invalid_credentials")) {
const { username } = err1.getContext("invalid_credentials");
}
// Check several ids at once — narrows to that subset
if (err2.hasOneOfIds(["invalid_credentials", "rate_limited"])) {
// ...
}
// All active ids
err2.getIds(); // ["invalid_credentials", "rate_limited"]

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",
});
const e = err_auth.fromId("invalid_credentials", { username: "alice" });
e.domain; // "err_auth"
e.message; // "Invalid credentials for: alice"
e.httpStatusCode; // 401
e.getIds(); // ["invalid_credentials"]

Next: Domain hierarchies →