在基于express.js的应用程序中集中error handling

我最近刚开始开发一个基于express.js的应用程序,它也使用pg模块(https://github.com/brianc/node-postgres)

我也花了大量的时间,阅读关于节点和expression方法的error handling,正确devise中间件的好处等等。然而,一个反复出现的问题仍然让我不知所措。

说,我有以下路由器的方法:

app.get("/:someThing/:someId", function(req, res, next) { pgClient.query("some SQL query", function(err, data) { if (err) { return next(err); } // some 500 handler will take it if (data.rows.length == 0) { next(); // send it over to a 404 handler } //finally, here we get the chance to do something with the data. //and send it over via res.json or something else }); }); 

如果我的阅读正确,这应该是正确的方法来做到这一点。 然而,我敢打赌,你也可以指出,即使在相同的路由器方法中,如果我们有多个嵌套的callback函数,反复重写也是太多了。

我一直在问自己,集中处理这种情况的最好方法是什么。 我所有的想法都涉及拦截pgClient.query方法。 在一个,查询方法将只是抛出错误,而不是传递给callback。 另一方面,对pgClient.query的调用将把路由器方法的下一个发送给pgClient。 然后截获的查询方法将知道如何处理下一个被传递给它。

从我所知道的情况来看,抛出错误并不是真正把它交给500个处理者的恰当方法。 另一方面,作为pgClient的一个选项,下面给出了一个很低层次的关于上述层次的知识,根据我的知识和经验,可以导致耦合,而且也不是很好。

你有什么build议?

您可以使用连接域中间件。 它适用于connectexpress并基于Doman API。

您需要添加connect-domain中间件作为堆栈中的第一个中间件。 就这样。 现在,您可以在asynchronous代码中的任何地方抛出错误,并且将使用域中间件处理它们,并传递给error handling程序。

简单的例子:

 // Some async function that can throw error var asyncFunction = function(callback) { process.nextTick(function() { if (Math.random() > 0.5) { throw new Error('Some error'); } callback(); }); }; var express = require('express'); var connectDomain = require('connect-domain'); var app = express(); app.use(connectDomain()); // We need to add router middleware before custom error handler app.use(app.router); // Common error handler (all errors will be passed here) app.use(function(err, req, res, next){ console.error(err.stack); res.send(500, 'Something broke!'); }); app.listen(3131); // Simple route app.get('/', function(req, res, next) { asyncFunction(function() { res.send(200, 'OK'); }); });