抛出自定义错误不会在日志中保留错误格式

时间:2016-04-16 13:23:40

标签: javascript

JavaScript,当throw出现内置错误时:

throw new Error("Something was wrong");

很好地显示文本 - 你不能告诉你扔了一个对象 enter image description here

但是,当通过子类化 Error对象(或其他错误对象)创建自定义错误时,抛出的错误在控制台中的显示方式不同。

因此,使用此代码:

var ImproperlyConfigured = function(message){
    this.name ="ImproperlyConfigured";
    this.message = message || "The object you tried to construct was improperly configured due to an unknown error";
}
ImproperlyConfigured.prototype = new Error();

以下是输出 enter image description here

我不喜欢显示对象属性(namemessage)的事实。事实上,我不喜欢我不明白为什么显示属性。

我已经google了一下,我觉得通过实现toString方法会有所帮助,但是,通过使用这种方法,错误的名称不再是红色的事实让我更加困惑

代码

var ImproperlyConfigured = function(message){
    this.name ="ImproperlyConfigured";
    this.message = message || "The object you tried to construct was improperly configured due to an unknown error";
    this.toString = function(){
        return this.message;
    }
}
ImproperlyConfigured.prototype = new Error();

输出: enter image description here

我想要实现的是标准错误,使用自定义错误,当然,不在console.error块中手动使用try...catch方法。

这可能吗?

1 个答案:

答案 0 :(得分:0)

正如Pointy正确指出(双关语),这里的问题不是JavaScript,而是JavaScript运行环境(在本例中为Google Chrome)。

在另一个环境(如Chromium,Firefox,NodeJS等)中,使用相同的代码可能会有所不同,具体取决于这些JavaScript主机处理这些情况的方式。