节点 assert.throws 未捕获异常 [英] Node assert.throws not catching exception
问题描述
鉴于此代码:
var assert = require('assert');
function boom(){
throw new Error('BOOM');
}
assert.throws( boom(), Error );
我得到这个输出,节点为 0.4.9:
I get this output, with node 0.4.9:
node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: BOOM
at boom ([EDITED]/assert.throws.test.js:4:9)
at Object.<anonymous> ([EDITED]/assert.throws.test.js:7:17)
at Module._compile (module.js:402:26)
at Object..js (module.js:408:10)
at Module.load (module.js:334:31)
at Function._load (module.js:293:12)
at Array.<anonymous> (module.js:421:10)
at EventEmitter._tickCallback (node.js:126:26)
对我来说,这意味着发生了未捕获的异常,而不是报告的、捕获的异常.查看文档,我注意到示例看起来更像这样:
This, to me, implies that an uncaught exception has occurred, as opposed to a reported, caught exception. Looking in the docs, I notice that the examples look more like this:
var assert = require('assert');
function boom(){
throw new Error('BOOM');
}
assert.throws( boom, Error );
但是你如何测试它是否在给定输入的情况下抛出异常?例如:
But how do you test if it throws an exception given a certain input? For example:
var assert = require('assert');
function boom(blowup){
if(blowup)
throw new Error('BOOM');
}
assert.throws( boom, Error );
这将失败.我做错了什么,或者除了我之外每个人都知道什么秘密?
This will fail. What am I doing wrong, or what secret does everybody know but me?
推荐答案
示例采用一个函数,而您的示例代码调用一个函数并传递结果.异常发生在断言甚至可以查看它之前.
The examples take a function, while your sample code calls a function and passes the result. The exception happens before the assert even gets to look at it.
将您的代码更改为:
var assert = require('assert');
function boom(){
throw new Error('BOOM');
}
assert.throws( boom, Error ); // note no parentheses
要传递参数,只需创建另一个函数.毕竟,这是javascript!
To pass parameters, just make another function. After all, this is javascript!
var assert = require('assert');
function boom(blowup){
if(blowup)
throw new Error('BOOM');
}
assert.throws( function() { boom(true); }, Error );
这篇关于节点 assert.throws 未捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!