@easyweb/errors
v1.1.0
Published
Shared HTTP error taxonomy for Easyweb microservices: typed error classes with machine-readable codes, and the express error-handling middleware that serializes them
Readme
@easyweb/errors
Shared HTTP error taxonomy for Easyweb microservices: typed error classes with machine-readable codes, and the express middleware that serializes them.
Previously these classes lived in @easyweb/authentication. They moved here in @easyweb/[email protected] — error handling is cross-cutting, and a service that needs ConflictError should not have to depend on a JWT package to get it.
Install
npm install @easyweb/errorsexpress@^5 is a peer dependency, owned by the consuming service.
Wiring
Mount the catch-all and the handler last, after every router:
import { errorHandler, notFoundHandler } from "@easyweb/errors";
import logger from "./lib/logger";
app.use("/auth", authRouter);
app.all(/.*/, notFoundHandler);
app.use(errorHandler({ logger }));Pass the service's pino instance. The default is console, which works but produces unstructured output with no service name, no redaction, and no request id.
| Option | Default | |
|---|---|---|
| logger | console | Anything with error and warn. |
| logClientErrors | false | Log 4xx at warn level. Off because client mistakes are not incidents. |
| includeRequestId | true | Include requestId in the body. |
| fallbackMessage | "Something went wrong" | Body text for an unrecognized error. |
Response shape
{
"errors": [
{ "message": "Email is already registered", "field": "email", "code": "CONFLICT" }
],
"requestId": "0f4d…" // omitted when requestContext has not run
}message and field predate this package and are unchanged. code is additive and is the only part clients should branch on — message is free-form English written at the throw site, and some of it is already Indonesian.
requestId comes from req.requestId, set by requestContext in @easyweb/authentication, and matches the x-request-id response header. It is read defensively, so this package does not depend on the auth package.
Classes
| Status | Class | Constructor |
|---|---|---|
| 400 | BadRequestError | (message) |
| 400 | RequestValidationError | (errors) — accepts { field, message } or { msg, path }, per entry |
| 401 | NotAuthorizedError | (message = "Not authorized") |
| 403 | ForbiddenError | (message = "Forbidden") |
| 404 | NotFoundError | () — unrouted path |
| 404 | ResourceNotFoundError | (resource, id?) — domain object |
| 409 | ConflictError | (message, field?) |
| 422 | UnprocessableEntityError | (message) |
| 429 | TooManyRequestsError | (message?, retryAfterSeconds?) |
| 500 | InternalServerError | (message = "Something went wrong") |
| 500 | DatabaseConnectionError | () |
| 502 | BadGatewayError | (message?) |
| 503 | ServiceUnavailableError | (message?, retryAfterSeconds?) |
| 504 | GatewayTimeoutError | (message?) |
retryAfterSeconds becomes a Retry-After header.
Picking one
- 401 vs 403 — 401 means "we do not know who you are"; 403 means "we do, and you may not". Returning 401 for a role failure sends the client round a re-authentication loop that cannot succeed.
- 400 vs 409 — 400 says the request was malformed. If the request was fine and the state conflicts (duplicate email, already-verified account), that is 409: retrying the identical request cannot help.
- 400 vs 404 —
BadRequestError("User not found")blames the caller for asking about something absent. UseResourceNotFoundError. Exception: during login, "no such user" is aNotAuthorizedError, or the endpoint becomes an account-enumeration oracle. - 500 vs 503 — 500 means our code broke. A dependency being temporarily down is 503, and orchestrators treat the two differently.
Behaviour of the handler
- A
CustomErroris serialized with its own status and body. - A body-parser
SyntaxError(malformed JSON) becomes 400, not 500. - A non-
CustomErrorcarrying a numericstatus/statusCodein[400,599]keeps it — several libraries in the stack set an accurate one. - Anything else is 500 with
fallbackMessage.
On branches 2–4 the original message and stack are never serialized: they may name a table, a query, or a secret. Only the status is trusted.
isCustomError
The handler branches on isCustomError(err), not err instanceof CustomError.
instanceof compares constructor identity, so it fails when two copies of this package exist in one process — for example a nested install under node_modules/@easyweb/authentication/node_modules/. The failure is silent and total: every error stops matching and turns into a generic 500, while types still check and the build still passes.
Two defences: @easyweb/authentication declares this package as a peerDependency so npm cannot nest it, and CustomError carries a __easywebError brand that isCustomError falls back to. If you add a package that depends on this one, declare it as a peer for the same reason.
Verify with:
npm ls @easyweb/errors # must show exactly one, deduped at the top levelPublishing
npm run build && npm publishbuild runs clean first. Without it a renamed or deleted source file leaves an orphan in dist/ that ships in the tarball.
