當你扔在一個函數的異常(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);
您能解釋更多關於Express直接調用的內容嗎? :d。 我是新手,知道很多東西 非常感謝:d – thelonglqd
我用完整的示例更新了我的答案,希望這有助於! – xaviert
非常感謝您的回答! 另外,app.get或者app.post(類似的東西)在傳遞給express的路由器api時,它們的錯誤也會被express表示(它發生在我的項目中:D) – thelonglqd