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

问题描述 投票:300回答:6

我想编写一个常见的错误处理程序,它将捕获在任何代码实例上故意抛出的自定义错误。

当我在下面的代码中做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"},我可以在其中访问错误属性。

有什么不同?

是否在代码中看到了差异?像字符串一样只是作为字符串和对象传递给对象,但语法会有所不同吗?

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

还有除上述两种方法之外的其他方法吗?

javascript object error-handling exception-handling throw
6个回答
191
投票

这是关于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块自动传输到catch块之前,您可以显式抛出自己的异常以强制按需发生,而不是等待6种类型的错误中的一种发生。这非常适合创建自己的错误定义,以及何时应将控制转移到catch。


69
投票

以下文章可能会更详细地说明哪个是更好的选择; throw 'An error'throw new Error('An error')

http://www.nczonline.net/blog/2009/03/10/the-art-of-throwing-javascript-errors-part-2/

它表明后者(new Error())更可靠,因为Internet Explorer和Safari(不确定版本)等浏览器在使用前者时无法正确报告消息。

这样做会导致抛出错误,但并非所有浏览器都以您期望的方式响应。 Firefox,Opera和Chrome均显示“未捕获的异常”消息,然后包含消息字符串。 Safari和Internet Explorer只是抛出“未捕获的异常”错误,并且根本不提供消息字符串。显然,从调试的角度来看,这是次优的。


64
投票

扔“我是邪恶的”

抛出将终止进一步执行并公开消息字符串以捕获错误。

try{
    throw 'I\'m Evil'
    console.log('You\'ll never reach to me', 123465)
}
catch(e){
    console.log(e); //I\'m Evil
}

投掷后的控制台永远不会达到终止的原因。

抛出新的错误(“我很甜蜜”)

throw new Error使用两个params名称和消息公开错误事件。它还终止进一步的执行

try{
     throw new Error('I\'m Evil')
     console.log('You\'ll never reach to me', 123465)
}
catch(e){
        console.log(e.name, e.message); //Error, I\'m Evil
}

30
投票

你首先提到这段代码:

throw new Error('sample')

然后在你的第一个例子中写道:

throw new Error({'hehe':'haha'}) 

第一个Error对象实际上可以工作,因为它期望一个字符串值,在本例中为'sample'。第二个不会,因为你试图传入一个对象,它期待一个字符串。

错误对象将具有“message”属性,该属性为“sample”。


5
投票

你可以把throw作为对象

throw ({message: 'This Failed'})

然后例如在你的try/catch

try {
//
} catch(e) {
    console.log(e); //{message: 'This Failed'}
    console.log(e.message); //This Failed
}

或者只是抛出一个字符串错误

throw ('Your error')

try {
//
} catch(e) {
    console.log(e); //Your error
}

throw new Error //only accept a string

3
投票

TLDR:它们是等价的。

// this:
const x = Error('I was created using a function call!');
​​​​// has the same functionality as this:
const y = new Error('I was constructed via the "new" keyword!');

来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error


0
投票

Error构造函数用于创建错误对象。发生运行时错误时抛出错误对象。 Error对象还可以用作用户定义的异常的基础对象。

用户定义的错误通过throw语句抛出。程序控制将传递给调用堆栈中的第一个catch块。

使用和不使用Error对象抛出错误的区别:


throw {'hehe':'haha'};

在chrome devtools中看起来像这样:

enter image description here

Chrome告诉我们,我们有一个未被捕获的错误,它只是一个JS对象。对象本身可能有关于错误的信息,但我们仍然不知道它来自何处。当我们处理代码并对其进行调试时,它们并不是很有用。


throw new Error({'hehe':'haha'}); 

在chrome devtools中看起来像这样:

enter image description here

使用Error对象抛出的错误在扩展时为我们提供了堆栈跟踪。这为我们提供了有价值的信息,其中错误来自于调试代码时通常是有价值的信息。进一步注意错误说[object Object],这是因为Error构造函数需要一个消息字符串作为第一个参数。当它收到一个对象时,它会将它强制转换成一个字符串。

© www.soinside.com 2019 - 2024. All rights reserved.