ExpressJS 中的错误处理

Error handling in ExpressJS

我想在我的 expressJS 应用程序中开发单点错误处理。
我在 expressJS 配置中添加了以下代码:

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


因此,应用程序中发生的任何错误都应执行上述函数,以便我可以以自定义方式处理错误。
但是,上述函数不会在 javascript 错误或以下代码上执行:

throw new Error('something broke!');

我已阅读:
http://expressjs.com/guide/error-handling.html and
http://derickbailey.com/2014/09/06/proper-error-handling-in-expressjs-route-handlers/
但是,我仍然无法在我的 expressJS 应用程序中进行一般错误处理。
谁能解释一下我将如何处理单点的任何应用程序错误?

实际上,您需要将错误处理放在路由器的末尾,

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

如果你有错误记录器,你必须把它放在错误处理的前面。

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

并且您可以定义多个错误处理中间件,每个错误处理捕获不同级别的错误。

不是express,是nodejs,你可以试试

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

因为"throw"是javascript,不受expressjs控制。

对于那些错误,比如 express 中的路由,你应该能够用 app.error 或 app.use(function(err .. 正如其他人所建议的那样,这也将可用 req, res 对象。

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

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

});

在express中,你通过调用带参数的next()来触发路由错误处理,如下:

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

调用 next() 将触发链中的下一个 middleware/handler。如果你向它传递一个参数(如 next(err) ),那么它将跳过下一个处理程序并触发错误处理中间件。

据我所知,如果你只是 throw 一个错误,它不会被 express 捕获,你可能会崩溃你的节点实例。

请记住,您可以根据需要拥有任意数量的错误处理程序:

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);
});