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

当我抛出新的错误('sample'),如下所示

try {
    throw new Error({'hehe':'haha'});
    // throw new Error('hehe');
} catch(e) {
    alert(e);
    console.log(e);
}

日志在Firefox中显示为错误:[object object],我无法解析该对象。

对于第二次抛出,日志显示为:错误:呵呵

然而当我这样做的时候

try {
    throw ({'hehe':'haha'});
} catch(e) {
    alert(e);
    console.log(e);
}

控制台显示为:对象{hehe="haha"},我可以在其中访问错误属性。

有什么不同?

区别是否如代码中所示?比如字符串会作为字符串传递而对象作为对象但语法会有所不同?

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

除了以上两种方法,还有别的办法吗?


当前回答

Throw something对对象和字符串都有效。但是它比另一种方法更不受支持。throw new Error("")将只对字符串起作用,并在catch块中将对象转化为无用的[Object obj]。

其他回答

Throw something对对象和字符串都有效。但是它比另一种方法更不受支持。throw new Error("")将只对字符串起作用,并在catch块中将对象转化为无用的[Object obj]。

这是相当古老的,但希望任何搜索它的人仍然可以从中学到东西:

首先,在javascript中,我们有一个叫做原始包装器的东西;原语包装器接受原语数据,并通过简单地使用“构造函数模式”以对象格式表示它。不过,在原语包装器中,您可以决定将数据作为对象类型返回,也可以将其作为原语类型返回(在这种情况下,您现在得到了一个让javascript提取原语值的go-ahead命令,在这种情况下,您不使用new关键字)。

总而言之:

throw "My error": this creates an Error object and returns the primitive data extracted from the constructor "this" object. And if you try checking the typeof in the catch block, it tells you its a primitive typeof "string" throw new Error("My error"): this returns you an object where you can access the error value from the message property. What simply happens here is that the "new keyword" constructs a "this" object and assign "{name:"Error",message:"..."}" to it and returns it. And when you try to check the typeof from the catch block, you will see a typeof "object".

注意:在显式地将自定义对象传递给throw的情况下,它的行为就像使用new关键字调用构造函数一样,因此,catch块将返回自定义对象而不是消息属性值。例如:throw {name:"RangeError",message:"range is out of scope",environment:" occurred in testing function"}。

总之,使用任何适合你的东西,你知道你在做什么。但对于我来说,如果我不需要太多的数据,而只是需要错误,那么我就使用原始返回器。

你首先提到了这段代码:

throw new Error('sample')

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

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

第一个Error对象实际上是有用的,因为它需要一个字符串值,在本例中是'sample'。第二个则不会,因为您正在试图传递一个对象,并且它期待一个字符串,并且不会显示有用的错误。

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

下面的文章可能会更详细地说明哪个是更好的选择;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只是抛出一个“未捕获的异常”错误,根本不提供消息字符串。显然,从调试的角度来看,这是次优的。

TLDR:它们是等价的Error(x) === new Error(x)。

// 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

throw和throw Error函数是等价的。但是当你捕获它们并将它们序列化到console.log时,它们的序列化方式并不完全相同:

throw 'Parameter is not a number!';
throw new Error('Parameter is not a number!');
throw Error('Parameter is not a number!');

Console.log(e)将产生2个不同的结果:

Parameter is not a number!
Error: Parameter is not a number!
Error: Parameter is not a number!