如何在nodejs和express中处理exception

在nodejs express来处理exception,检查callback中的err为:

if(err!==null){ next(new Error ('Erro Message')); } 

而这又会调用express的error handling程序中间件。

 app.use(function(err, req, res, next){ if(!err) return next(); console.log('<-------Error Occured ----->'); res.send(500, JSON.stringify(err, ['stack', 'message'])); }); 

但是为了调用next(err),我不得不通过所有的层遍历所有callback方法的下一个参考。 我觉得这是一个凌乱的办法。 有没有更好的方法来处理exception,并使用事件或域发送适当的响应。

你应该总是把路由/控制器中的错误委托给error handling器,然后调用next(所以你可以在一个地方处理它们,而不是把它们分散在你的应用程序中)。

这是一个例子:

 app.get('/', function(req, res, next) { db.findUser(req.params.userId, function(err, uid) { if (err) { return next(err); } /* ... */ }); }); /* Your custom error handler */ app.use(function(err, req, res, next) { // always log the error here // send different response based on content type res.format({ 'text/plain': function(){ res.status(500).send('500 - Internal Server Error'); }, 'text/html': function(){ res.status(500).send('<h1>Internal Server Error</h1>'); }, 'application/json': function(){ res.send({ error: 'internal_error' }); } }); }); 

注意:您不必检查error handling程序中的错误参数,因为它始终存在。

也很重要:总是做return next(err); 因为你不希望成功的代码被执行。

你的代码示例都是有缺陷的:在第一个中你没有使用return next(err) ,在第二个中你使用了return next(err) ,所以后面的代码不应该处理错误(因为它会如果出现错误,永远不要到达那里),而应该是“成功”的代码。

Express中的错误页面示例显示了处理错误的规范方法:

https://github.com/visionmedia/express/blob/master/examples/error-pages/index.js

 // error-handling middleware, take the same form // as regular middleware, however they require an // arity of 4, aka the signature (err, req, res, next). // when connect has an error, it will invoke ONLY error-handling // middleware. // If we were to next() here any remaining non-error-handling // middleware would then be executed, or if we next(err) to // continue passing the error, only error-handling middleware // would remain being executed, however here // we simply respond with an error page.