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();
我想要实现的是标准错误,使用自定义错误,当然,不在console.error
块中手动使用try...catch
方法。
这可能吗?
答案 0 :(得分:0)
正如Pointy正确指出(双关语),这里的问题不是JavaScript,而是JavaScript运行环境(在本例中为Google Chrome)。
在另一个环境(如Chromium,Firefox,NodeJS等)中,使用相同的代码可能会有所不同,具体取决于这些JavaScript主机处理这些情况的方式。