http请求上的express.jserror handling

如何处理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); }); 

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

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

error handling中间件的定义就像普通的中间件一样,但是必须定义一个4的元素,即签名(err,req,res,next):

Expresserror handling

例如代码:

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