Reputation: 323
This guide suggests the custom handling of the errors in Express.js through this code:
app.use(function(err, req, res, next) {
// Do logging and user-friendly error message display
console.error(err);
res.status(500).send({status:500, message: 'internal error', type:'internal'});
})
It doesn't work as expected: it launches always the same "Cannot GET" error instead of the customized one. How to handle 404 and other types of errors with Express?
Upvotes: 3
Views: 6620
Reputation: 565
Not Found or 404 is not by default an application error, the handler which you have to define gets called only when you pass the error in the next argument of any route. For handling 404, you should use a handler without an error.
app.use(function(req, res, next) {
// Do logging and user-friendly error message display.
console.log('Route does not exist')
res.status(500).send({
status: 500,
message: 'internal error',
type: 'internal'
})
})
Note: The above handler should be placed after all the valid routes and above the error handler.
If, however, you want to handle both 404 and other errors with same response you could explicitly generate an error for 404. For instance:
app.get('/someRoute',function(req, res, next) {
// If some error occurs pass the error to next.
next(new Error('error'))
// Otherwise just return the response.
})
app.use(function(req, res, next) {
// Do logging and user-friendly error message display.
console.log('Route does not exist')
next(new Error('Not Found'))
})
app.use(function(err, req, res, next) {
// Do logging and user-friendly error message display
console.error(err)
res.status(500).send({
status: 500,
message: 'internal error',
type: 'internal'
})
})
This way, your error handler is also called for not found errors and for all the other business logic errors.
Upvotes: 15
Reputation: 396
I'm not entirely sure which part of the error message you're attempting to customize, however, if you're looking to change the reason phrase try this:
app.use(function(err, req, res, next) {
// console.log(err)
res.statusMessage = "Route does not exist";
res.status(401).end()
}
You can replace .end()
with .send()
if you do want to include a body.
Upvotes: 0