快递错误将处理哪个错误,而uncaughtException错误处理程序将处理哪个错误?

时间:2015-11-05 09:46:33

标签: node.js express uncaught-exception

在我的服务中使用express nodejs。我知道快速错误处理程序,错误的回调函数

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

我们也可以通过

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

实际上,一些uncaughtException将表达错误处理程序而不是uncaughtException处理程序。

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

非常感谢

1 个答案:

答案 0 :(得分:2)

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