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

当我抛出新的错误('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]。

其他回答

The Error class includes debugging information (as properties of its instances), such as the error's call stack. JS interpreters know how to serialise those properties into an informative error message string, and they can also be consumed by debugging software - such as browser dev tools - to construct a more informative GUI representation of the error. This is why it's generally more useful to throw an instance of the Error class rather than simply throwing, for example, a string describing the error, or a number representing an error code.

使用自定义错误

特别有用的是创建自己的Error子类,它允许您使用描述性名称和机器可读的惟一标识不同类型的错误……

调试线索, 信息,以便更好地面向用户的错误消息,或者 帮助从错误中恢复的信息。

然后,在处理错误时,可以使用简洁的instanceof操作符来检查发生了什么类型的错误。例如:

class ShoesTooBig extends Error {}

class DangerousWaterCurrent extends Error {
    constructor(waterSpeed){
        super(`These waters are moving at ${waterSpeed} metres per second - too fast to cross!`) // Provide a `message` argument to the Error() constructor
        this.waterSpeed = waterSpeed // This passes some context about why/how the error occurred back to whichever function is going to catch & handle it
    }
}

// ...later...

try {
    swimAcrossRiver(footwear, river)
} catch (thrownValue) {
    if (thrownValue instanceof DangerousWaterCurrent) {
        constructDam(river, thrownValue.waterSpeed)
    } else {
        throw thrownValue // "Re-throw" the error back up the execution chain, for someone else to handle
    }
}

new Error() vs Error()

There is a "convenient" shorthand way to make an instance of Error: by calling Error(message), instead of new Error(message), the way you'd make an instance of a normal class. This is a deliberate exception, inserted by the language designers, to the rule. There are similar shorthands for other in-language classes, like Number() and String(). They also let you call these classes with () as if they were functions, not classes. JS doesn't allow normal classes to do this, even though they're all actually functions under the syntactical sugar of "classes". Try in a REPL:

> class E extends Error {}
undefined
> Error(); 'a value'
"a value"
> E(); 'a value'
Uncaught TypeError: Class constructor E cannot be invoked without 'new'
    at <anonymous>:2:1

就我个人而言,我认为这个决定是错误的,因为它为JavaScript规则添加了更多的例外。而不是c++ /Java的new关键字,简单地调用一个类,就好像它是一个函数(如在Number("abc123")))应该执行类的构造函数,并将其绑定到实例,就像通常发生的new关键字一样(这是Python的语法工作方式,它最终更易于阅读和方便)。

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

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

有和没有error对象时抛出错误的区别:


throw {'hehe':'haha'};

在chrome中,devtools是这样的:

Chrome告诉我们,我们有一个未捕获的错误,这只是一个JS对象。对象本身可能有关于错误的信息,但我们仍然不知道它来自哪里。在我们处理代码和调试它的时候,这不是很有用。


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

在chrome中,devtools是这样的:

与error对象一起抛出的错误在展开堆栈时提供堆栈跟踪。这为我们提供了有价值的信息,错误准确地来自哪里,这在调试代码时通常是有价值的信息。进一步注意,错误说的是[object object],这是因为error构造函数期望一个消息字符串作为第一个参数。当它接收到一个对象时,它会将其强制转换为一个字符串。

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

首先,在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"}。

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

TLDR

throw new Error('problem')捕获错误发生位置的许多属性。

抛出“问题”则不然

new Error('message')捕获执行堆栈+其他

使用Error对象允许您在抛出错误时捕获执行堆栈。因此,当错误被传递到错误处理树时,这个堆栈快照也会被传递。

因此,在我的代码库中插入throw“test error”会导致:

而throw new Error('test Error ')会导致:

您可以看到本机Error对象在抛出错误时捕获堆栈,并使捕获错误的任何对象都可以使用它。这使我在调试时更容易跟踪问题。

除此之外,它还捕获诸如fileName、lineNumber和columnNumber等属性。

如果您使用堆栈跟踪,则异常跟踪器将为您记录日志

在这种情况下,堆栈将被打印到浏览器控制台,但如果你使用的是Javascript错误记录工具,如Appsignal或Bugsnag,那么堆栈也将在它们中可用。如果你检查错误对象,你可以直接访问堆栈快照:

err = new Error('test')
err.stack

我用来决定使用哪种格式的启发式方法

当我不打算捕获异常时,我使用new Error('problem')

当我抛出一个错误,因为应用程序中发生了一些意想不到的或超出范围的事情,假设本地数据存储损坏了,我可能不想处理它,但我确实想标记它。在本例中,我将使用Error对象,这样我就有了堆栈快照。

通过使用throw new Error('Datastore is corrupt '),更容易追踪到所发生的事情。

当我计划捕获异常时,我使用抛出'problem'

在重新阅读这篇文章时,我认为下一部分需要一些谨慎。通常,非常具体地说明要捕获的错误是一个好主意,否则您可能会捕获您真正想要一直冒泡的东西。一般来说,创建特定的错误类型并捕获特定的错误(或消息字符串)可能更好。这使得你没有预料到的错误浮出水面。”

如果错误是我计划捕获和处理的预期错误,那么我将不会从堆栈快照中得到太多用处。

假设我使用一个http服务,它返回一个500的http代码。我可以将此视为一个错误,我抛出“responseccode =500”,然后随后捕获并处理。

你可以把它作为对象抛出

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