【发布时间】:2012-02-27 16:41:45
【问题描述】:
我想编写一个通用的错误处理程序,它将捕获在任何代码实例中故意抛出的自定义错误。
当我在下面的代码中throw new Error('sample') 时
try {
throw new Error({'hehe':'haha'});
// throw new Error('hehe');
} catch(e) {
alert(e);
console.log(e);
}
日志在 Firefox 中显示为 Error: [object Object],我无法解析该对象。
对于第二个throw,日志显示为:Error: hehe
而当我这样做时
try {
throw ({'hehe':'haha'});
} catch(e) {
alert(e);
console.log(e);
}
控制台显示为:Object { hehe="haha"},我可以在其中访问错误属性。
有什么区别?
是否如代码中所见的差异? like string 将仅作为字符串传递,将 object 作为对象传递,但语法会有所不同?
我还没有探索过抛出错误对象……我只做过抛出字符串。
除了上面提到的两种方法,还有其他方法吗?
【问题讨论】:
-
throw new Error({prop:val}) 的问题在于它不是一个有效的 Error 构造。错误具有 Hemant 所讨论的已知属性。
-
基于 ecma262 它们都是相同的:
creates and initializes a new Error object when called as a function rather than as a constructor. Thus the function call Error(…) is equivalent to the object creation expression new Error(…) with the same arguments.Spec in tc39.es/ecma262/#sec-error-constructor
标签: javascript object error-handling exception-handling throw