Last active
October 3, 2019 03:58
-
-
Save ezy/ae1ccdc1e96238a8c0e7a32f941259b4 to your computer and use it in GitHub Desktop.
Express middleware error handling with ease
This file contains hidden or 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
// catch 404 and forward to error handler | |
app.use((req, res, next) => { | |
res.status(404).json({ message: 'API not found' }); | |
next(); | |
}); | |
// error handler, send stacktrace only during development | |
app.use((err, req, res, next) => { | |
if (res.headersSent) { | |
return next(err); | |
} | |
const status = err.status ? err.status : httpStatus.INTERNAL_SERVER_ERROR; | |
const sendAsOutput = { message: err.message }; | |
if (config.env === 'development') { | |
sendAsOutput.error = err; | |
} | |
return res.status(status).json(sendAsOutput); | |
}); |
This file contains hidden or 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
// helper file for generating error in next() | |
const genError = (message, status, error) => ({ | |
error, | |
message, | |
status, | |
}); | |
module.exports = { genError }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment