2016-10-10 46 views
0

我應該在POST請求中使用表達式錯誤處理中間件函數來處理缺少字段的情況嗎?什麼時候在NODE中使用錯誤中間件功能

function (req, res, next) { 

    if (!req.body.mandatoryField){ 
     var err = new Error("missing field); 
     err.status(400); 
     next(err); // send response from error middleware 
    } 

} 

或者我應該將它保存爲catually拋出異常情況:

model.save(function(err){ 
    next(err); 
} 

換句話說,是扔壞輸入錯誤在POST請求矯枉過正?

或者我應該直接回應一個400狀態響應,而不會引發錯誤。

回答

0

我不會。我會保存中間件錯誤處理以將錯誤發送到日誌記錄服務。通常情況下,您會攔截一般錯誤並在繼續之前將其記錄下來。如果您將其作爲中間件來執行,則會攔截每個請求,而這對大多數情況來說都是不必要和脆弱的。

通常,這些驗證會在使用jQuery的客戶端上發生,這樣您就可以保存到db的行程。

這裏是我如何使用中間件來處理錯誤:

//uncaught exception in the application/api, etc. Express will pass the err param. This doesn;t look for specific errors, it will log any general error it sees. 
app.use(function(err, req, res, next) { 
    //send to logging service. 
    next(err); 
}); 
//uncaught exception in Node 
if (process.env.NODE_ENV === 'production' || appConfig.env === 'production') { // [2] 
    process.on('uncaughtException', function(err) { 
     console.error(err.stack); // [3] 
     //log error, send notification, etc 

    }, function(err) { 
     if (err) {console.error(err);} 
     process.exit(1); // [5] 
    }); 
} 
0

這真的取決於你的API的設計和誰將會消耗它。如果您正在編寫自己的前端並可以處理HTTP 400錯誤響應的含義,那麼只要讓數據庫出錯就可以簡單得多。

如果你想更細化的驗證,然後做它在路線(或通過中間件)是要走的路:)

相關問題