简体   繁体   English

使用expressjs处理异步瀑布中的错误

[英]handling error in async waterfall with expressjs

I don't see why expressjs don't handle error when it's throw in async.waterfall 我不明白为什么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');
});

When i GET /error , expressjs print a nice error without crash serveur but when i GET /asyncerror it's a classic throw, print on stdout with server crash .. 当我GET /错误时,expressjs打印出一个漂亮的错误而没有崩溃服务但是当我获取/ asyncerror它是一个经典的抛出,在服务器崩溃的stdout上打印..

Thx for your help. 谢谢你的帮助。

It's because Express never has the opportunity to catch the exception that's thrown in the /asyncerror example as you're throwing it from within an async callback context and not an Express middleware context. 这是因为Express永远不会有机会捕获/asyncerror示例中抛出的异常,因为您从async回调上下文而不是Express中间件上下文中抛出异常。 In general, if you don't want an error condition in an async function to crash your node app, report the error via the callback instead of throwing it. 通常,如果您不希望异步函数中的错误条件导致节点应用程序崩溃,请通过回调报告错误而不是抛出错误。 In this case you can call the next parameter that your app.get callback is receiving but you're not using. 在这种情况下,您可以调用app.get回调接收的next参数但您没有使用。 Try this instead: 试试这个:

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'));
        });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM