I have the following coffeescript code:
try
do something
catch error
log something
throw error
我应该使用throw new Error(error)
还是throw error
?
它们之间有什么区别?
I have the following coffeescript code:
try
do something
catch error
log something
throw error
我应该使用throw new Error(error)
还是throw error
?
它们之间有什么区别?
与C#或Java等其他语言相同:
throw error
抛出相同的错误对象throw new Error(error)
将其包装到新的错误对象中。后者在Java中使用,例如当您需要将checked Exception转换为未检查的异常时。在JavaScript中,您不需要包装异常,因为这会使堆栈跟踪稍微长一点且不太美观。编辑: 还有一些安全性问题。这是一个例子:
function noWrap() {
try {
var o = {}; o.nonexistingMethod();
} catch (error) {
throw error;
}
}
function wrap() {
try {
var o = {}; o.nonexistingMethod();
} catch (error) {
throw new Error(error);
}
}
noWrap()
会产生以下错误信息:"TypeError: Object #<Object> has no method 'nonexistingMethod'"
// with error.arguments === ['nonexistingMethod', o]
调用wrap()
会产生以下错误消息:
"Error: TypeError: Object #<Object> has no method 'nonexistingMethod'"
// with error.arguments === undefined
通过使用一个包装的错误对象,我们可以隐藏原始错误的arguments
。假设您正在编写以下之一:
在上述所有情况下,为了保持安全性,应该包装您的Error
对象。否则,您可能会意外地泄漏对内部对象、函数和变量的引用。
编辑2:关于堆栈跟踪。这两种变体都保留了它们。这里是一个工作示例,我在Chrome中得到以下堆栈跟踪:
// No wrapping:
TypeError: Object #<Object> has no method 'nonexistingMethod'
at noWrap (http://fiddle.jshell.net/listochkin/tJzCF/show/:22:23)
at http://fiddle.jshell.net/listochkin/tJzCF/show/:37:5
at http://fiddle.jshell.net/js/lib/mootools-core-1.4.5-nocompat.js:3901:62
at http://fiddle.jshell.net/js/lib/mootools-core-1.4.5-nocompat.js:3915:20
// Wrapping:
Error: TypeError: Object #<Object> has no method 'nonexistingMethod'
at wrap (http://fiddle.jshell.net/listochkin/tJzCF/show/:32:15)
at http://fiddle.jshell.net/listochkin/tJzCF/show/:44:5
at http://fiddle.jshell.net/js/lib/mootools-core-1.4.5-nocompat.js:3901:62
at http://fiddle.jshell.net/js/lib/mootools-core-1.4.5-nocompat.js:3915:20
stack
属性。我不知道其他浏览器的情况。 - Andrei Андрей Листочкин