2012-09-26 42 views
4

我不明白爲什麼當它的投async.waterfall在異步瀑布與expressjs處理錯誤

var express = require('express') 
, app = express.createServer() 
, async = require('async'); 

app.use(express.errorHandler({ 
    dumpExceptions: true, 
    showStack: true 
})); 

app.get('/error', function(req, res){ 
    throw Error('Aie'); 
}); 

app.get('/asyncerror', function(req, res){ 
    var that = this; 
    async.waterfall([ 
     function(next){ 
      console.log('1'); 
      next("42", "2"); 
     }, 
     function(arg, next) { 
      console.log(arg); 
      res.json('ok'); 
     } 
     ], function(err){ 
      console.log(this); 
      throw Error('Aie'); 
     }); 
}); 

app.listen(8888, function(){ 
    console.log('Listen on 0.0.0.0:8888'); 
}); 

當我拿到/錯誤expressjs不處理錯誤,expressjs打印一個不錯的錯誤,而不崩潰serveur但是當我GET/asyncerror這是一個經典的投擲,與服務器崩潰在標準輸出打印..

Thx爲您的幫助。

回答

3

這是因爲快遞從來沒有機會趕上公司在/asyncerror例子如您是從async回調背景下的快速中間件環境中,而不是把它扔引發的異常。通常,如果您不希望異步函數中的錯誤條件導致您的節點應用程序崩潰,請通過回調報告錯誤而不是拋出錯誤。在這種情況下,您可以調用next參數,即您的app.get回調正在接收但您沒有使用。試試這個:

app.get('/asyncerror', function(req, res, next){ 
    var that = this; 
    async.waterfall([ 
     function(next){ 
      console.log('1'); 
      next("42", "2"); 
     }, 
     function(arg, next) { 
      console.log(arg); 
      res.json('ok'); 
      next(); 
     } 
     ], function(err){ 
      console.log(this); 
      next(Error('Aie')); 
     }); 
});