Skip to content

Instantly share code, notes, and snippets.

@codfish
Last active January 4, 2019 18:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codfish/2d19163d3d96fae0b12174d38722f85c to your computer and use it in GitHub Desktop.
Save codfish/2d19163d3d96fae0b12174d38722f85c to your computer and use it in GitHub Desktop.
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