我可以在JavaScript中为用户定义的异常定义自定义类型吗?如果是,我该怎么做?
当前回答
function MyError(message) {
this.message = message;
}
MyError.prototype = new Error;
这允许使用像..
try {
something();
} catch(e) {
if(e instanceof MyError)
doSomethingElse();
else if(e instanceof Error)
andNowForSomethingCompletelyDifferent();
}
其他回答
从WebReference:
throw {
name: "System Error",
level: "Show Stopper",
message: "Error detected. Please contact the system administrator.",
htmlMessage: "Error detected. Please contact the <a href=\"mailto:sysadmin@acme-widgets.com\">system administrator</a>.",
toString: function(){return this.name + ": " + this.message;}
};
用于ES2015类的asselin答案的替代方案
class InvalidArgumentException extends Error {
constructor(message) {
super();
Error.captureStackTrace(this, this.constructor);
this.name = "InvalidArgumentException";
this.message = message;
}
}
使用throw语句。
JavaScript并不关心异常类型(就像Java一样)。 JavaScript只是注意到,有一个异常,当你捕捉到它,你可以“看看”异常“说”什么。
如果你有不同的异常类型,你必须抛出,我建议使用变量包含异常的字符串/对象,即消息。在需要它的地方使用“throw myException”,在catch中,将捕获的异常与myException进行比较。
ES6
使用新的类和扩展关键字,现在更容易:
class CustomError extends Error {
constructor(message) {
super(message);
//something
}
}
function MyError(message) {
this.message = message;
}
MyError.prototype = new Error;
这允许使用像..
try {
something();
} catch(e) {
if(e instanceof MyError)
doSomethingElse();
else if(e instanceof Error)
andNowForSomethingCompletelyDifferent();
}