gpt4 book ai didi

node.js - 在基于 express.js 的应用程序中集中处理错误

转载 作者:搜寻专家 更新时间:2023-10-31 22:22:53 24 4
gpt4 key购买 nike

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

我还花了很多时间阅读有关 Node 和快速方法错误处理、正确设计中间件的好处等内容。然而,一个反复出现的问题仍然困扰着我,没有解决方案。

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

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

如果我没看错的话,这应该是正确的做法。然而,我打赌你也可以承认,一遍又一遍重写的样板太多了……一遍又一遍,即使是在完全相同的路由器方法中,以防我们有多个嵌套回调。

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

据我所知,四处抛出错误并不是将错误发送给 500 个处理程序的正确方法。另一方面,将 next 作为 pgClient 的选项传递给如此低的级别,但根据我的知识和经验,这会导致耦合,也不是很好。

你有什么建议?

最佳答案

您可以使用 connect-domain中间件。它适用于 connectexpress 并基于 Doman API。

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

简单的例子:

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

关于node.js - 在基于 express.js 的应用程序中集中处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14080887/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com