如何在nodejs和express中的单个位置处理异常

时间:2013-11-14 10:55:08

标签: node.js events error-handling express

在nodejs表示处理异常时,请将回调中的错误检查为:

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

反过来调用express的错误处理程序中间件。

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),我不得不在所有层的所有回调方法中传递 next 的引用。我发现这是一个混乱的方法。有没有更好的方法来处理异常并使用事件或域发送适当的响应。

2 个答案:

答案 0 :(得分:1)

您应该始终通过调用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' });
    }
  });
});

注意:您不必在错误处理程序中检查err param,因为它始终存在。

同样非常重要:始终执行return next(err);因为您不希望执行成功代码。

您的代码示例都存在缺陷:在第一个中您没有使用return next(err),在第二个中您使用了return next(err),因此后面的代码不应该处理错误(因为它永远不会出现,以防出现错误),而应该是“成功”代码。

答案 1 :(得分:0)

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.
相关问题