[英]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();
我不喜欢显示对象属性( name
和message
)的事实。 实际上,我不喜欢我不理解为什么显示属性。
我已经用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.