哪些错误将由 express error 处理,哪些由 uncaughtException 错误处理程序处理?

Which error will be handled by express error and which by uncaughtException error handler?

在我的服务中使用 express nodejs。我知道 express error handler,err first

的回调函数
app.use(function(err, req, res, next)

我们也可以通过

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

其实有些uncaughtException会去express error handler而不是uncaughtException handler。

请帮忙告诉我哪些错误将由 express 处理,哪些由 uncaughtException 处理程序处理?

非常感谢

当您在直接从 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);