简体   繁体   中英

Error handling in ExpressJS

I want to develop error handling at single point in my expressJS app.
I have added following code in expressJS configuration :

app.use(app.router);
app.use(function (err, req, res, next) {
    console.error('ExpressJS : error!!!');
});


So, any error occurred in app then above function should get execute so that I can handle error in custom way.
But, above function is not getting execute on javascript error or on following code :

throw new Error('something broke!');

I have read :
http://expressjs.com/guide/error-handling.html and
http://derickbailey.com/2014/09/06/proper-error-handling-in-expressjs-route-handlers/
But, still I am not able to make generic error handling in my expressJS app.
Can anyone explain how I will handle any app error at single point?

Not by express, but nodejs, you can try

process.on('uncaughtException', function(err) {
  console.log(err);
});

Because "throw" is javascript, not under expressjs control.

For those errors, like routing in express, you should able to catch with app.error or app.use(function(err .. as other advised, which would available req, res object too.

app.error(function(err, req, res, next){
    //check error information and respond accordingly
});

//newer versions
app.use(function(err, req, res, next) {

});

actually , you need put the error-handling in the end of the router ,

app.use(function(err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

if you have the error logger , you must put it in front of the error-handling .

app.use(bodyParser());
app.use(methodOverride());
app.use(logErrors);            // log the error
app.use(clientErrorHandler);   // catch the client error , maybe part of the router
app.use(errorHandler);         // catch the error occured in the whole router

and you may define several error-handling middleware , each error-handling catch different level error .

In express, you trigger the route error handling by calling next() with a parameter, as follows:

app.get('/api/resource',function(req, res, next) {
   //some code, then err occurs
   next(err);
})

calling next() will trigger the next middleware/handler in your chain. If you pass a parameter to it (as in next(err) ), then it will skip the next handlers and trigger the error handling middleware.

As far as I know, if you simply throw an error, it won't be caught by express and you may crash your node instance.

Remember you can have as many error handlers as you need:

app.use(function (err, req, res, next) {
    //do some processing...
    //let's say you want more error middleware to trigger, then keep on calling next with a parameter
    next(err);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM