集中在基于express.js的应用程序中的错误处理 [英] Centralizing error handling in an express.js-based app

查看:126
本文介绍了集中在基于express.js的应用程序中的错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我也花了大量的时间,阅读关于节点和快速方法错误处理,正确设计中间件的好处等等。然而,一个反复出现的问题仍然令我无法解决。



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

  get(/:someThing /:someId,function(req,res,next){
pgClient.query(some SQL query,function(err,data){
if(err)返回next(err);} //大约500个处理程序将使用
if(data.rows.length == 0){
next(); //将其发送到404处理程序
$

//最后,我们有机会用数据做一些事情
//并通过res.json或其他东西
}发送它) ;
});

如果我正确阅读,这应该是正确的方法。然而,我敢打赌,你也可以认为它是太多的样板重写一遍又一遍,甚至在相同的路由器方法,以防万一我们有多个嵌套回调。



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



从我所知道的,抛出错误并不是真正适合的方法到500个处理程序。另一方面,passin接下来作为pgClient的一个选择,给出了这样一个低级别的知识,基于我的知识和经验,可以导致耦合,并且也不是很好。 >

你建议什么?您可以使用连接域中间件。它适用于 connect express ,并基于 Doman API。



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



简单示例:

  //一些可以抛出错误的异步函数
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());
//我们需要在自定义错误处理程序
app.use(app.router)之前添加路由器中间件;

//常见的错误处理程序(所有错误将在此传递)
app.use(function(err,req,res,next){
console.error(err。 stack);
res.send(500,Something broke!);
});

app.listen(3131);

//简单路由
app.get('/',function(req,res,next){
asyncFunction(function(){
res.send (200,'OK');
});
});


I just recently started working on an express.js based application, which also uses the pg module (https://github.com/brianc/node-postgres)

I also spent a significant amount of time, reading about node and express approach error handling, the benefits of properly designing middleware, etc. Yet, a recurring problem is still buzzing me without a solution.

Say, I have the following router method:

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

If I've read correctly, this should be the proper way to do it. Yet, I bet you can also admt that it is too much of boilerplate to rewrite over and over ... and over again, even in the very same router method, in case we have multiple nested callbacks.

I've been asking myself what the best way to handle such a situation centrally would be. All of my ideas involve intercepting the pgClient.query method. In one, the query method will simply throw the error instead of passing it to the callback. In another, the call to the pgClient.query will send the router method's next to pgClient. Then the intercepted query method will know how to deal with the next being passed to it.

From what I know, throwing errors around is not really the appropriate way to get it to the 500 handlers. On another hand, passin next as an option to pgClient, gives such a low level a lot of knowledge about the the layers above, which based on my knowledge and experience, can lead to coupling, and is not very good either.

What do you suggest?

解决方案

You can use connect-domain middleware. It works with connect and express and based on Doman API.

You need to add connect-domain middleware as first middleware in stack. Thats all. Now you can throw errors everywhere in your async code and they will be handled with domain middleware and passed to express error handler.

Simple example:

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

这篇关于集中在基于express.js的应用程序中的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆