【问题标题】:how do you throw a custom error class in Javascript?你如何在 Javascript 中抛出自定义错误类?
【发布时间】:2013-01-15 18:29:27
【问题描述】:

在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.
}

但它不起作用(得到“未定义”和错误)

这可能吗?

【问题讨论】:

    标签: javascript exception throw


    【解决方案1】:

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

    【讨论】:

    • 太棒了。直接对象的投掷似乎有效。我读到的唯一问题是浏览器不能很好地处理它。我的 MyError 和你的 MyError 有什么区别?我猜它的范围。你的没有这个,所以是私人的。
    • 在您的 MyError 函数中,所有变量都在该对象范围内。
    猜你喜欢
    • 1970-01-01
    • 2021-11-02
    • 2016-06-14
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 1970-01-01
    • 2018-01-08
    • 1970-01-01
    相关资源
    最近更新 更多