嵌套回调函数中的Trapping AssertionError
Trapping AssertionError in nested callback function
我正在为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
它可能很快就会被弃用,但希望会有一个具有类似功能的替代品,因为域模块现在正在节省我的时间,因为我没有其他方法来捕获错误,因为错误可能是由我的用户代码生成的,而不是我的代码。
相关文章:
- console.assert失败时中断chrome调试器
- 如何在JavaScript中使用Mocha和assert.throws测试参数的值
- Node.js assert.deep等于2个值
- 使用自定义断言帮助程序对cli扩展assert进行ember-cli扩展
- Node.js assert.throws with async functions (Promises)
- assert.throws on asynchronous method
- Nitghwatch.js -- assert.hidden 在页面的一部分上
- 带有nodejs的mocha为assert(false)而不是error断言挂起/超时
- 嵌套回调函数中的Trapping AssertionError
- 浏览器中的Mocha:如何使用chai.assert获取报告
- 一个不需要输入错误消息的assert函数
- 在node.js中启用/禁用assert语句的简单方法
- 为什么Node.js Assert没有notOk()方法?
- assert failed: InvalidValueError: setContent:不是字符串
- Assert数组包含Chai数组
- 当其中一个值是函数时,mocha assert. deeequal
- 在摩卡失败的“断言”中;In assert函数导致超时而不是失败
- 在assert抛出中匹配regexp
- assert (request .assert)在nodejs中是如何工作的?
- Gulp:控制台错误,assert.js:90抛出新的assert.AssertionError