javascript - 你如何在 Javascript 中抛出自定义错误类?

标签 javascript exception throw

在 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/

相关文章:

javascript - 如何从完整的 URL 获取 Slideshare 的嵌入 ID?

javascript - map 未显示在网页上(Google map /地点 API)

c# - 多次重试的好方法

c# - 定义可以从工具包 API 中抛出的异常

c++ - throw, try {} catch {} 应该如何在现实世界中使用?

C#: 'throw'是否退出当前函数?

javascript - IE8 JavaScript 问题

javascript - 比较 jquery timepicker 值

java - java中永远不会出现的异常

java - 如何修复 Java :26: error: illegal start of type (throws)