簡體   English   中英

對http請求的express.js錯誤處理

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM