Reputation: 1931
The express doc says:
Note that the default error handler can get triggered if you call next() with an error in your code more than once, even if custom error handling middleware is in place.
I think it means if we call next(error)
inside our custom error handler, then the control passes on to next error handler (which may be the express' default one if we already has not registered more custom error handlers).
Is my understanding correct?
Upvotes: 2
Views: 464
Reputation: 11
Yes, you have understood it correctly. However, it is not useful to call the default error handler inside the custom error handler as the only purpose of the custom error handler is to send the errors to the user according to you i.e. in your format.
You can implement a custom global error handler by defining an error-handling middleware after all the app.use
calls and in the callback function, you can create your own logic like sending different errors in dev
or prod
environment. You can also set up different user-friendly messages.
app.use(function (err, req, res, next) {
err.statusCode = err.statusCode || 500;
err.status = err.status || 'error';
if (process.env.NODE_ENV === 'development') {
// a custom function for sending dev errors
sendErrorDev(err, res);
} else if (process.env.NODE_ENV === 'production') {
// logic for creating different user-friendly errors
sendErrorProd(error, res);
}
})
And in both sendErrorDev
and sendErrorProd
functions, you can send the errors by the res
object.
Upvotes: 1