ExpressJS中的error handling
我想在我的expressJS应用程序的单点开发error handling。
我在expressJSconfiguration中添加了以下代码:
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应用程序中进行通用的error handling。
任何人都可以解释我将如何处理任何应用程序错误在单点?
不是通过expression,而是nodejs,你可以试试
process.on('uncaughtException', function(err) { console.log(err); });
因为“扔”是javascript,不受expressjs的控制。
对于这些错误,如快速路由,你应该能够赶上app.error或app.use(function(错误..其他build议,这将可用的REQ,水库对象了。
app.error(function(err, req, res, next){ //check error information and respond accordingly }); //newer versions app.use(function(err, req, res, next) { });
实际上,你需要把error handling放在路由器的末端,
app.use(function(err, req, res, next) { console.error(err.stack); res.status(500).send('Something broke!'); });
如果你有错误logging器,你必须把它放在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
你可以定义几个error handling中间件,每个error handling捕获不同级别的错误。
在express中,通过用参数调用next()
触发路由error handling,如下所示:
app.get('/api/resource',function(req, res, next) { //some code, then err occurs next(err); })
调用next()
将触发链中的下一个中间件/处理程序。 如果你传递一个参数(如next(err)
),那么它将跳过下一个处理程序并触发error handling中间件。
据我所知,如果你只是throw
一个错误,它不会被明确捕获,你可能会崩溃你的节点实例。
请记住,您可以拥有尽可能多的error handling程序:
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); });