Skip to content

Instantly share code, notes, and snippets.

@codfish codfish/error-handling.js
Last active Jan 4, 2019

Embed
What would you like to do?
Default express api error handling middleware.
/**
* Handle application errors.
*
* NOTE: 500 status code is returned by default.
*
* To properly leverage this middleware, rather than return responses in your routes,
* simply set a response status in the route and then pass the error object to `next`.
* This middleware will catch that error and handle it in a consistent way across
* the entire application. For example:
*
* try {
* // look up something here
* } catch (err) {
* res.status(404);
* return next(err);
* }
*
* @see {@link https://expressjs.com/en/guide/error-handling.html}
*/
export function defaultErrorHandler(err, req, res, next) {
if (res.headersSent) {
return next(err);
}
console.error(err);
return res.status((res.statusCode > 200 && res.statusCode) || 500).send({ message: err.message });
}
// use like so:
// The default error handler should come AFTER all routes to catch
// all application errors and handle them in a consistent manner.
app.use(defaultErrorHandler);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.