繁体   English   中英

引发自定义错误不会保留日志中的错误格式

[英]Throwing custom error doesn't preserve Error formatting in the log

JavaScript,当throw诸如此类的内置错误时:

throw new Error("Something was wrong");

很好地显示文字-您不能告诉您扔了一个物体 在此处输入图片说明

但是,通过子类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();

以下是输出 在此处输入图片说明

我不喜欢显示对象属性( 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();

输出: 在此处输入图片说明

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

这可能吗?

, the issue here is not with JavaScript, but rather with the environment JavaScript is running (in this case, Google Chrome). 正如Pointy正确指出的那样 ,这里的问题不在于JavaScript,而在于运行JavaScript的环境(在这种情况下为Google Chrome)。

在其他环境(例如Chromium,Firefox,NodeJS等)中,行为可能会有所不同,使用相同的代码,具体取决于这些JavaScript主机如何处理这些情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM