node.js - 使用 expressjs 处理异步 waterfall 中的错误

标签 node.js error-handling express waterfall node-async

我不明白为什么 expressjs 在 async.waterfall 中抛出错误时不处理错误

var express = require('express')
, app = express.createServer()
, async = require('async');

app.use(express.errorHandler({
    dumpExceptions: true,
    showStack: true
}));

app.get('/error', function(req, res){
    throw Error('Aie');
});

app.get('/asyncerror', function(req, res){
    var that = this;
    async.waterfall([
        function(next){
            console.log('1');
            next("42", "2");
        },
        function(arg, next) {
            console.log(arg);
            res.json('ok');
        }
        ], function(err){
            console.log(this);
            throw Error('Aie');
        });
});

app.listen(8888, function(){
    console.log('Listen on 0.0.0.0:8888');
});

当我 GET/error 时,expressjs 会打印一个很好的错误,而不会导致服务器崩溃,但是当我 GET/asyncerror 时,这是一个经典的错误,在标准输出上打印服务器崩溃..

感谢您的帮助。

最佳答案

这是因为 Express 从来没有机会捕获 /asyncerror 示例中抛出的异常,因为您是从 async 回调上下文中抛出它,而不是表达中间件上下文。通常,如果您不希望异步函数中的错误条件使您的 Node 应用程序崩溃,请通过回调报告错误而不是抛出错误。在这种情况下,您可以调用 app.get 回调正在接收但您未使用的 next 参数。试试这个:

app.get('/asyncerror', function(req, res, next){
    var that = this;
    async.waterfall([
        function(next){
            console.log('1');
            next("42", "2");
        },
        function(arg, next) {
            console.log(arg);
            res.json('ok');
            next();
        }
        ], function(err){
            console.log(this);
            next(Error('Aie'));
        });
});

关于node.js - 使用 expressjs 处理异步 waterfall 中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12598559/

相关文章:

javascript - 我如何使用 Node.js Express 压缩中间件?

node.js - 快速 session 动态 cookie 域

node.js - 如何通过本地网络与 Electron/ express 应用程序共享数据?

node.js - Xcode cloud 突然无法链接 Node 和安装依赖项

javascript - 如何从nodejs中的内部函数获取值

android - 处理 Android 自定义内容提供程序中的(跨进程)异常

java - 使用 Spring 时,如何在错误 500 页面中打印堆栈跟踪?

node.js - 使用请求解析查询数组并使用 express 接收

node.js - NodeJS 无法访问回调中的变量

php - PHP Oracle : oci_connect doesn't show error