嵌套回调函数中的Trapping AssertionError

Trapping AssertionError in nested callback function

本文关键字:Trapping AssertionError 回调 函数 嵌套      更新时间:2023-09-26

我正在为Node.js编写一个更新的测试库,并试图正确地捕获测试回调中发生的错误

由于某些原因,以下代码没有捕获断言错误:

process.on('uncaughtException',function(err){
    console.error(err);  //an instance of AssertionError will show up here
});

[file1,file2,file2].forEach(function (file) {

        self.it('[test] ' + path.basename(file), {
            parallel:true
        },function testCallback(done) {
            var jsonDataForEnrichment = require(file);
            request({
                url: serverEndpoint,
                json: true,
                body: jsonDataForEnrichment,
                method: 'POST'
            }, function (error, response, body) {
                if (error) {
                    done(error);
                }
                else {
                    assert(response.statusCode == 201, "Error: Response Code"); //this throws an error, which is OK of course
                    done();
                }
            });
        });
    });

我处理回调(我在上面把它命名为"testCallback"),代码是:

                try {
                    if (!inDebugMode) {
                        var err = new Error('timed out - ' + test.cb);
                        var timer = setTimeout(function () {
                            test.timedOut = true;
                            cb(err);
                        }, 5000);
                    }
                    test.cb.apply({
                        data: test.data,
                        desc: test.desc,
                        testId: test.testId
                    }, [function (err) {   //this anonymous function is passed as the done functon
                        cb(err);
                    }]);
                }
                catch (err) {  //assertion error is not caught here
                    console.log(err.stack);
                    cb(err);
                }

我认为问题在于,由异步函数(如请求模块中的异步函数)产生的回调无法通过简单的错误处理来捕获。捕捉错误的最佳方法是什么?

我应该充实一下process.on('uncaughtException')处理程序吗?或者有更好的方法吗?

处理这一问题的最佳方法似乎是Node.js域,一个核心模块

https://nodejs.org/api/domain.html

它可能很快就会被弃用,但希望会有一个具有类似功能的替代品,因为域模块现在正在节省我的时间,因为我没有其他方法来捕获错误,因为错误可能是由我的用户代码生成的,而不是我的代码。