2015-11-05 162 views
0

在我使用express nodejs的服務中。我知道明確的錯誤處理程序,與ERR第一哪個錯誤將由express錯誤和uncaughtException錯誤處理程序處理?

app.use(function(err, req, res, next) 

回調函數,我們可以通過

process.on('uncaughtException', function(err) {} 

其實處理uncaughtException此外,一些uncaughtException會去表達錯誤處理程序不uncaughtException處理程序。

請幫忙告訴我哪個錯誤將由express處理,由uncaughtException處理程序處理?

非常感謝

回答

2

當你扔在一個函數的異常(throw new Error(...)),這是直接從快速調用,它將被逮住,並轉發給您的錯誤處理程序。發生這種情況是因爲代碼周圍有一個try-catch塊。

app.get("/throw", function(request, response, next) { 
    throw new Error("Error thrown in scope of this function. Express.js will delegate it to error handler.") 
}); 

當你扔在一個函數的異常不直接由快遞(延遲或異步代碼)呼籲,有沒有可用的catch塊捕獲這個錯誤並妥善處理。例如,如果你有一些代碼被異步執行:

app.get("/uncaught", function(request, response, next) { 
    // Simulate async callback using setTimeout. 
    // (Querying the database for example). 
    setTimeout(function() { 
     throw new Error("Error thrown without surrounding try/catch. Express.js cannot catch it."); 
    }, 250); 
}); 

這個錯誤不會被快速被獲取(並轉發到錯誤處理程序),因爲有解決這個代碼沒有包裝try/catch塊。在這種情況下,將會觸發未捕獲的異常處理程序。

在一般情況下,如果遇到從中你無法恢復的錯誤,使用next(error)正確地轉發這個錯誤你的錯誤處理程序中間件:

app.get("/next", function(request, response, next) { 
    // Simulate async callback using setTimeout. 
    // (Querying the database for example). 
    setTimeout(function() { 
     next(new Error("Error always forwarded to the error handler.")); 
    }, 250); 
}); 

下面是一個玩弄一個完整的例子:

var express = require('express'); 

var app = express(); 

app.get("/throw", function(request, response, next) { 
    throw new Error("Error thrown in scope of this function. Express.js will delegate it to error handler.") 
}); 

app.get("/uncaught", function(request, response, next) { 
    // Simulate async callback using setTimeout. 
    // (Querying the database for example). 
    setTimeout(function() { 
     throw new Error("Error thrown without surrounding try/catch. Express.js cannot catch it."); 
    }, 250); 
}); 

app.get("/next", function(request, response, next) { 
    // Simulate async callback using setTimeout. 
    // (Querying the database for example). 
    setTimeout(function() { 
     next(new Error("Error always forwarded to the error handler.")); 
    }, 250); 
}); 


app.use(function(error, request, response, next) { 
    console.log("Error handler: ", error); 
}); 

process.on("uncaughtException", function(error) { 
    console.log("Uncaught exception: ", error); 
}); 

// Starting the web server 
app.listen(3000); 
+0

您能解釋更多關於Express直接調用的內容嗎? :d。 我是新手,知道很多東西 非常感謝:d – thelonglqd

+0

我用完整的示例更新了我的答案,希望這有助於! – xaviert

+0

非常感謝您的回答! 另外,app.get或者app.post(類似的東西)在傳遞給express的路由器api時,它們的錯誤也會被express表示(它發生在我的項目中:D) – thelonglqd