Errors
Handlers and middlewares return their errors, built with the helpers of @dotpress/core. This page lists them, the errors Dotpress produces itself, and how to report the unexpected ones. For the principles, see Returned errors.
Returning an error
Without a message, each uses the standard reason phrase (Not Found).
Custom errors
errorResponse(status, code, message, data) builds any other error. Use stable codes: clients test them.
data is sent to the client: never put internal details in it.
All helpers return an HttpError, which a handler or a middleware can also throw, with the same result. isHttpError(value) recognizes one.
Errors of your services
HTTP errors belong to the routes. A service never throws an HttpError: it returns undefined when nothing is found, and throws its own error when a business rule is broken. The handler translates it:
When several routes call the same service, share the translation in a function of the feature:
The service stays usable from a worker or a script, and the client only receives messages written for it. A business error left untranslated is a 500, without details: a forgotten case shows up in onError, not in the response. See the design decision.
Errors produced by Dotpress
These responses use the standard format too, and get the CORS headers: a browser client can read them.
Unexpected errors
An exception that is not an HttpError is unexpected: a bug, a database failure, a timeout. Dotpress:
- logs it with the request logger, so the log line carries the request ID;
- passes it to the
onErrorhooks; - answers
500 INTERNAL_ERROR, without any detail: an exception message can reveal a query, a path or a secret.
The response carries the X-Request-ID header: a client reporting a problem gives it, and you find the log line.
Reporting errors
onError receives every unexpected error, with the request context (undefined when the error happened outside a route):
Plugins add their own hooks with api.onError(). A failing hook is logged, and never changes the response.
Details in development
exposeErrors: true adds the name, message and stack of the error to the data of 500 responses, and the issues when a response does not match its schema:
Never enable exposeErrors in production. Dotpress never reads NODE_ENV or any environment variable itself: the decision is yours, explicit.
Errors of native middlewares
Errors passed to next(error) by native Express middlewares are converted to the standard format: a client error (a status from 400 to 499) keeps its status, anything else is a 500 reported to onError.
isDev is replaced by exposeErrors, and onException by onError. A thrown HttpError now gives the same response as a returned one (Dotpress 1 answered 500), and the 404 and 500 produced by the framework use the standard format.