Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customized error handling in Express.js

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?

like image 465
M-elman Avatar asked May 31 '26 06:05

M-elman


1 Answers

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.

like image 104
pulankit Avatar answered Jun 01 '26 20:06

pulankit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!