Last active
January 4, 2019 18:03
-
-
Save codfish/2d19163d3d96fae0b12174d38722f85c to your computer and use it in GitHub Desktop.
Default express api error handling middleware.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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