3

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?

2 Answers 2

15

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, I got it. But can I specify a status code and a message for 404 errors in res.status? And, generally, for different types of errors?
Yes you can do that, you can create a helper function which basically returns the status code and error message based on type of error and then u could simply use that helper function for decorating your response with proper status codes and messages
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.