例如:
- function runWithoutThrowing(func) {
- try {
- func();
- } catch (e) {
- console.log('There was an error, but I will not throw it.');
- console.log('The error\'s message was: ' + e.message)
- }
- }
- function funcThatThrowsError() {
- throw new TypeError('I am a TypeError.');
- }
- runWithoutThrowing(funcThatThrowsError);
如不雅用户传递给函数 runWithoutThrowing 的参数抛出了一个缺点对象, 膳绫擎的代码能正常捕获缺点. 然后, 如不雅是抛出一个字符串, 就会碰着一些问题了:
在 Node 的 REPL 模式中运行上述代码会获得如下输出:
- function runWithoutThrowing(func) {
- try {
- func();
- } catch (e) {
- console.log('There was an error, but I will not throw it.');
- console.log('The error\'s message was: ' + e.message)
- }
- }
- function funcThatThrowsString() {
- throw 'I am a String.';
- }
- runWithoutThrowing(funcThatThrowsString);
如今第二个 console.log 会输出undefined. 这看起来不是很重要, 但如不雅你须要确保 Error 对象有一个特定的属性或者用另一种方法来处理 Error 对象的特定属性(例如 Chai的throws断言的做法), 你就得做大年夜量的工作来确保法度榜样的┞俘确运行.
同时, 如不雅抛出的不是 Error 对象, 也就获取不到 stack 属性.
Errors 也可以被作为其它对象, 你也不必抛出它们, 这也是为什么大年夜多半回调函数把 Errors 作为第一个参数的原因. 例如: