简体   繁体   English

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

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

JavaScript, when throw -ing a built-in error as such: JavaScript,当throw诸如此类的内置错误时:

throw new Error("Something was wrong");

displays the text nicely - you can't tell you threw an object 很好地显示文字-您不能告诉您扔了一个物体 在此处输入图片说明

However, when creating a custom error by subclassing the Error object (or other error object for that matter), the thrown error is not displayed the same way in the console. 但是,通过子类Error对象(或与此相关的其他错误对象)来创建自定义错误时,抛出的错误在控制台中的显示方式不同。

So, by using this code: 因此,通过使用以下代码:

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();

The following is the output 以下是输出 在此处输入图片说明

I don't like the fact that the object properties ( name and message ) are shown. 我不喜欢显示对象属性( namemessage )的事实。 In fact, I don't like that I don't understand why the properties are shown. 实际上,我不喜欢我不理解为什么显示属性。

I've googled a bit and I got the feeling that by implementing a toString method will help but, by using this method, the fact that the name of the error is no longer in red puzzles me even more. 我已经用Google搜索了一下,我感觉到通过实现toString方法会有所帮助,但是通过使用此方法,错误名称不再是红色的事实使我更加困惑。

Code

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();

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

What I would like to achieve is a standard looking error, by the use of custom error and, of course, by not using the console.error method manually in a try...catch block. 我想实现的是一个标准外观错误,方法是使用自定义错误,当然也不要在try...catch块中手动使用console.error方法。

Is this possible? 这可能吗?

As Pointy correctly pointed out (pun intended) , 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)。

In another environment (like Chromium, Firefox, NodeJS, etc.) the behavior will likely be different, using the same code, depending on how those JavaScript hosts are handling these cases. 在其他环境(例如Chromium,Firefox,NodeJS等)中,行为可能会有所不同,使用相同的代码,具体取决于这些JavaScript主机如何处理这些情况。

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

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