[英]how do you throw a custom error class in Javascript?
在JS中,您可以引發“新錯誤(消息)”,但是如果您想檢測異常的類型並對消息進行其他操作,則並非易事。
這篇文章: http : //www.nczonline.net/blog/2009/03/10/the-art-of-throwing-javascript-errors-part-2/
表示您可以執行以下操作:
function MyError(message){
this.message=messsage;
this.name="MyError";
this.poo="poo";
}
MyError.prototype = new Error();
try{
alert("hello hal");
throw new MyError("wibble");
} catch (er) {
alert (er.poo); // undefined.
alert (er instanceof MyError); // false
alert (er.name); // ReferenceError.
}
但這不起作用(獲取“ undefined”和false)
這有可能嗎?
道格拉斯·克羅克福德(Douglas Crockford)建議拋出以下錯誤:
throw{
name: "SomeErrorName",
message: "This is the error message",
poo: "this is poo?"
}
然后您可以輕松地說:
try {
throw{
name: "SomeErrorName",
message: "This is the error message",
poo: "this is poo?"
}
}
catch(e){
//prints "this is poo?"
console.log(e.poo)
}
如果您真的想使用MyError Function方法,它可能應該看起來像這樣:
function MyError(message){
var message = message;
var name = "MyError";
var poo = "poo";
return{
message: message,
name: name,
poo: poo
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.