Not Found or 404 is not by default an application errerror, the handler which you have definedto define gets called only when you pass the error in the next argument of any route. For handling 404 You, you should use a handler without erran 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' })
})
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:- Above The above handler should be placed after all the valid routes and above the error handler.
ifIf, however, you want to handle both 404 and other errors with same response you could explicitly generate an error for 404, Something like. For instance:
app.get('/someRoute',function(req,res,next){
//if some error occures 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' })
})
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.