[英]express.js error handling on http requests
如何處理http請求中的錯誤?
這里將完整的錯誤返回給客戶端。如何將錯誤寫入日志並將Fatal error
返回給客戶端?
快遞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);
});
錯誤處理程序的.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);
});
錯誤處理中間件的定義與常規中間件一樣,但必須使用4的arity定義,即簽名(err,req,res,next):
例如代碼:
app.use(function(err, req, res, next){
console.error(err.stack);
res.send(500, 'Something broke!');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.