javascript - `throw new Error` 和 `throw someObject` 有什么区别?

标签 javascript object error-handling exception-handling throw

我想编写一个通用错误处理程序,它可以捕获在任何代码实例中故意抛出的自定义错误。

当我 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 将仅作为字符串传递,将对象作为对象传递,但语法会有所不同?

我还没有探索过抛出错误对象......我只做过抛出字符串。

除了上面提到的两种方法,还有其他方法吗?

最佳答案

javascript中'throw new Error'和'throw someObject'的区别在于throw new Error将传递给它的错误包装成以下格式-

{ name: 'Error', message: 'String you pass in the constructor' }

throw someObject 将按原样抛出对象,并且不允许从 try block 执行任何进一步的代码,即与 throw new Error 相同。

这里有一个很好的解释The Error object and throwing your own errors

错误对象

在发生错误时我们可以从中提取什么?所有浏览器中的Error对象都支持以下两个属性:

  • name:错误的名称,或者更具体地说,错误所属的构造函数的名称。

  • message:错误描述,此描述因浏览器而异。

name 属性可以返回六个可能的值,如前所述,它们对应于错误构造函数的名称。它们是:

Error Name          Description

EvalError           An error in the eval() function has occurred.

RangeError          Out of range number value has occurred.

ReferenceError      An illegal reference has occurred.

SyntaxError         A syntax error within code inside the eval() function has occurred.
                    All other syntax errors are not caught by try/catch/finally, and will
                    trigger the default browser error message associated with the error. 
                    To catch actual syntax errors, you may use the onerror event.

TypeError           An error in the expected variable type has occurred.

URIError            An error when encoding or decoding the URI has occurred 
                   (ie: when calling encodeURI()).

抛出您自己的错误(异常)

在控制自动从 try block 转移到 catch block 之前,无需等待 6 种错误类型之一发生,您还可以显式抛出自己的异常以强制其按需发生。这对于创建您自己的错误定义以及何时应将控制权转移给 catch 非常有用。

关于javascript - `throw new Error` 和 `throw someObject` 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9156176/

相关文章:

javascript - 如何根据部分键值匹配重新排序 JS 对象

python - 在Django项目中获取TypeError错误

javascript - 如何将溢出的 div 滚动到某个主题标签( anchor )?

javascript - 我可以使用 forEach 使数组的每个元素成为一个新对象吗?

javascript - 从对象键构建字符串

powershell - Powershell-如何从Word文档中保存单个页面?

error-handling - 如何隐藏猫的错误?

javascript - JS Axios - 发生错误时如何获取响应正文?

javascript - 如何从 api 动态填充日历标记的日期 - React Native,redux

javascript - jQuery 循环在特定位置暂停