对http请求的express.js错误处理

时间:2014-06-23 17:25:17

标签: node.js express

如何处理http请求中的错误?

此处将完整错误返回给客户端。如何将错误写入日志并将Fatal error返回给客户端?

Express v4.4.4

var express = require('express'),
    app = express(),
    domain = require('domain'),
    port = 3000;

app.use(function(err, req, res, next){
    console.error(err.stack);
    res.send('Fatal error!', 500);
});

app.get('/', function(req, res){
    var d = domain.create();
    d.on('error', function(err){
        console.error('Error', err);

        res.send('Fatal error!', 500);
    });
    d.add(req);
    d.add(res);
    d.run(function(){
        //  a is undefined
        a.ddd();

        res.send('Success!');
    });
})
.listen(port, function(){
    console.log('Express server listening on port '+port);
});

2 个答案:

答案 0 :(得分:3)

错误处理程序的.use需要位于底部,可能会导致错误的routes / handlers / middlewhare之后。然后从其他地方调用next(错误)而不是直接返回错误消息

// this comes first
app.get('/', function(req, res, next){ // note the addition of next
    var d = domain.create();
    d.on('error', function(err){
        next(err); // pass the error on to the next middleware
    });
    // ... 
});

// this comes last
app.use(function(err, req, res, next){
    console.error(err.stack);
    res.send('Fatal error!', 500);
});

答案 1 :(得分:0)

错误处理中间件的定义与常规中间件一样,但必须使用4的arity定义,即签名(err,req,res,next):

Express Error Handling

例如代码:

app.use(function(err, req, res, next){
  console.error(err.stack);
  res.send(500, 'Something broke!');
});
相关问题