Skip to content

Instantly share code, notes, and snippets.

@ezy
Last active October 3, 2019 03:58
Show Gist options
  • Save ezy/ae1ccdc1e96238a8c0e7a32f941259b4 to your computer and use it in GitHub Desktop.
Save ezy/ae1ccdc1e96238a8c0e7a32f941259b4 to your computer and use it in GitHub Desktop.
Express middleware error handling with ease
// 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);
});
// 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