2016-11-13 46 views
2

比方說,我已經定義了以下中間件和路由處理程序:Express.js:從路由處理函數調用下一個(錯誤)是否調用全局錯誤處理中間件?

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

app.get('/test',function(req,res) { 
    //some error happens here, and ther "error" object is defined 
    next(error); 
}); 

Doe的錯誤處理中間件被調用?

如果不是,將錯誤處理中間件如果

  • 錯誤處理中間件被下面的路由處理程序定義的叫什麼?我用throw error;代替next(error);
  • 以上兩者是否屬實?

或者我應該做這樣的事情:

//route.js 
module.exports=function(req,res,next) { 
    //error happens here 
    next(error); 
} 

//errorHandler.js 
module.exports=function(err,req,res,next) { 
    res.status(500).send('Something broke!'); 
} 

//app.js 
var route=require('route'); 
var errorHandler=require('erorHandler'); 
app.get('/test',[route,errorHandler]); 

我現在有點糊塗了......

回答

2

中間件的順序,app.get,app.post等重要事項,它們按照您的代碼中添加的順序進行處理。

所以當你定義它像你這樣

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

app.get('/test',function(req,res) { 
    //some error happens here, and ther "error" object is defined 
    next(error); 
}); 

第一個中間件將捕獲的所有請求,並返回狀態500,它從來沒有達到app.get('test'...

錯誤處理程序應始終在底部的代碼,所以如果在某些路由處理程序中出現錯誤,您可以調用next(error),並且錯誤處理程序將以類似於您的消息的方式響應客戶端res.status(500).send('Something broke!');

而且這個

app.get('/test',[route,errorHandler]); 

是actualy不好,因爲你需要在每一個航線使用它

好:

app.get('/test',function(req,res,next) { 
    //some error happens here, and ther "error" object is defined 
    next(error); 
}); 

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

app.listen(8000); 
+0

啊,所以未來(錯誤)將進入錯誤處理中間件,即使它沒有在路線中定義「下一個」是什麼? – Alex

+0

對不起,這是一個錯誤,'next'必須在回調函數app.get('/ test',function(req,res,next)'否則會出錯'「next」不是函數' – Molda

+0

''下一個(錯誤)''會用''req,res,next''簽名忽略中間件,並用'err,req,res,next''簽名直接進入下一個中間件? – Alex