在 JS 中,你可以抛出一个“new Error(message)”,但是如果你想检测异常的类型并对消息做一些不同的事情,就不是那么容易了。
这篇文章: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 MyError(message){
var message = message;
var name = "MyError";
var poo = "poo";
return{
message: message,
name: name,
poo: poo
}
};
关于javascript - 你如何在 Javascript 中抛出自定义错误类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14629443/