Deviopath › Node.js

Error Handler Middleware

Medium · Errors

In Express, a final error-handling middleware turns any thrown error into an HTTP response. Write toErrorResponse(error, env) that does this. error is plain data: { name, message, statusCode? }.

Pick the status code:

- If statusCode is a whole number from 400 to 599, use it.

- Otherwise map by name: ValidationError → 400, UnauthorizedError → 401, ForbiddenError → 403, NotFoundError → 404.

- Anything else → 500.

Return { status, body: { error, message } } where error is the error name (or "Error" if it has no name).

Server errors can leak secrets, so when the status is 500 or higher AND env is "production", the body must be { error: "InternalServerError", message: "Internal Server Error" } instead.

Next: Paginate a List Endpoint