If your controllers aren't asynchronous, you can simply add error handler after you registered all of your route
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
throw new Error('Something went wrong');
});
// Add more routes here
// Error handler
app.use(function (err, req, res, next) {
// All errors from non-async route above will be handled here
res.status(500).send(err.message)
});
app.listen(port);
If your controllers are asynchronous, you need to add a custom middleware to your controller to handle async error. The middleware example is taken from this answer
const express = require('express');
const app = express();
const port = 3000;
// Error handler middleware for async controller
const asyncHandler = fn => (req, res, next) => {
return Promise
.resolve(fn(req, res, next))
.catch(next);
};
app.get('/', asyncHandler(async (req, res) => {
throw new Error("Something went wrong!");
}));
// Add more routes here
// Error handler
app.use(function (err, req, res, next) {
// All errors from async & non-async route above will be handled here
res.status(500).send(err.message)
})
app.listen(port);