我想在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和http://derickbailey.com/2014/09/06/proper-error-handling-in-expressjs-route-handlers/
但是,我仍然无法在expressJS应用程序中进行通用错误处理。
任何人都可以解释我将如何在单点处理任何应用程序错误?
答案 0 :(得分:5)
不是快递,而是nodejs,你可以尝试
process.on('uncaughtException', function(err) {
console.log(err);
});
因为" throw"是javascript,而不是在expressjs控制下。
对于那些错误,比如在express中路由,你应该能够捕获app.error或app.use(函数(错误...如其他建议的那样,也可以使用req,res对象。
app.error(function(err, req, res, next){
//check error information and respond accordingly
});
//newer versions
app.use(function(err, req, res, next) {
});
答案 1 :(得分:0)
实际上,您需要将错误处理放在路由器的末尾,
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
您可以定义多个错误处理中间件,每个错误处理都会捕获不同级别的错误。
答案 2 :(得分:0)
在express中,通过使用参数调用next()
来触发路径错误处理,如下所示:
app.get('/api/resource',function(req, res, next) {
//some code, then err occurs
next(err);
})
调用next()
将触发链中的下一个中间件/处理程序。如果您向其传递参数(如在next(err)
中),那么它将跳过下一个处理程序并触发错误处理中间件。
据我所知,如果你只是throw
一个错误,它就不会被快递捕获,你可能会崩溃你的节点实例。
请记住,您可以根据需要拥有尽可能多的错误处理程序:
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);
});