我可以在 JavaScript 中为用户定义的异常定义自定义类型吗?如果是这样,我该怎么做?
自定义异常类型
IT技术
javascript
exception
                    2021-03-16 22:14:12
                
                    
                
            
        6个回答
            从Web引用:
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;} 
}; 
您应该创建一个典型地从 Error 继承的自定义异常。例如:
function InvalidArgumentException(message) {
    this.message = message;
    // Use V8's native method if available, otherwise fallback
    if ("captureStackTrace" in Error)
        Error.captureStackTrace(this, InvalidArgumentException);
    else
        this.stack = (new Error()).stack;
}
InvalidArgumentException.prototype = Object.create(Error.prototype);
InvalidArgumentException.prototype.name = "InvalidArgumentException";
InvalidArgumentException.prototype.constructor = InvalidArgumentException;
这基本上是上面发布的内容的简化版本,增强了堆栈跟踪在 Firefox 和其他浏览器上的工作。它满足他发布的相同测试:
用法:
throw new InvalidArgumentException();
var err = new InvalidArgumentException("Not yet...");
它的行为是预期的:
err instanceof InvalidArgumentException          // -> true
err instanceof Error                             // -> true
InvalidArgumentException.prototype.isPrototypeOf(err) // -> true
Error.prototype.isPrototypeOf(err)               // -> true
err.constructor.name                             // -> InvalidArgumentException
err.name                                         // -> InvalidArgumentException
err.message                                      // -> Not yet...
err.toString()                                   // -> InvalidArgumentException: Not yet...
err.stack                                        // -> works fine!
您可以实现自己的异常及其处理,例如:
// define exceptions "classes" 
function NotNumberException() {}
function NotPositiveNumberException() {}
// try some code
try {
    // some function/code that can throw
    if (isNaN(value))
        throw new NotNumberException();
    else
    if (value < 0)
        throw new NotPositiveNumberException();
}
catch (e) {
    if (e instanceof NotNumberException) {
        alert("not a number");
    }
    else
    if (e instanceof NotPositiveNumberException) {
        alert("not a positive number");
    }
}
还有另一种捕获类型异常的语法,尽管这不适用于所有浏览器(例如不适用于 IE):
// define exceptions "classes" 
function NotNumberException() {}
function NotPositiveNumberException() {}
// try some code
try {
    // some function/code that can throw
    if (isNaN(value))
        throw new NotNumberException();
    else
    if (value < 0)
        throw new NotPositiveNumberException();
}
catch (e if e instanceof NotNumberException) {
    alert("not a number");
}
catch (e if e instanceof NotPositiveNumberException) {
    alert("not a positive number");
}
是的。你可以抛出任何你想要的东西:整数、字符串、对象等等。如果你想抛出一个对象,那么只需创建一个新对象,就像在其他情况下创建一个对象一样,然后抛出它。Mozilla 的 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();
}
其它你可能感兴趣的问题