当您在直接从 Express 调用的函数中抛出异常 (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.")
});
当您在不是直接从 Express 调用的函数(延迟或异步代码)中抛出异常时,没有可用的 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);
});
Express 不会捕获此错误(并转发给错误处理程序),因为此代码周围没有包装 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);