我可以在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();
}

其他回答

我经常使用带有原型继承的方法。重写toString()的好处是,像Firebug这样的工具将记录实际信息,而不是将[object object]记录到控制台,以查找未捕获的异常。

使用instanceof来确定异常的类型。

main.js

// just an exemplary namespace
var ns = ns || {};

// include JavaScript of the following
// source files here (e.g. by concatenation)

var someId = 42;
throw new ns.DuplicateIdException('Another item with ID ' +
    someId + ' has been created');
// Firebug console:
// uncaught exception: [Duplicate ID] Another item with ID 42 has been created

Exception.js

ns.Exception = function() {
}

/**
 * Form a string of relevant information.
 *
 * When providing this method, tools like Firebug show the returned 
 * string instead of [object Object] for uncaught exceptions.
 *
 * @return {String} information about the exception
 */
ns.Exception.prototype.toString = function() {
    var name = this.name || 'unknown';
    var message = this.message || 'no description';
    return '[' + name + '] ' + message;
};

DuplicateIdException.js

ns.DuplicateIdException = function(message) {
    this.name = 'Duplicate ID';
    this.message = message;
};

ns.DuplicateIdException.prototype = new ns.Exception();

使用throw语句。

JavaScript并不关心异常类型(就像Java一样)。 JavaScript只是注意到,有一个异常,当你捕捉到它,你可以“看看”异常“说”什么。

如果你有不同的异常类型,你必须抛出,我建议使用变量包含异常的字符串/对象,即消息。在需要它的地方使用“throw myException”,在catch中,将捕获的异常与myException进行比较。

是的。你可以抛出任何你想抛出的东西:整数、字符串、对象等等。如果要抛出一个对象,那么只需创建一个新对象,就像在其他情况下创建一个对象一样,然后抛出它。Mozilla的Javascript参考中有几个例子。

//create error object
var error = new Object();
error.reason="some reason!";

//business function
function exception(){
    try{
        throw error;
    }catch(err){
        err.reason;
    }
}

现在我们设置,添加原因或任何我们想要的属性到错误对象并检索它。通过使误差更合理。

从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;} 
};