Javascript自定义异常

Javascript自定义异常,javascript,Javascript,我已经尝试了几天,研究如何在try/catch中创建自定义异常 以下是我试图做的: 我的html页面中包含了一个JS文件。JS文件定义了一个自定义对象,以及该对象的定义方法 接下来,在html页面中,我将执行以下操作: try { MyObj = new CustomObj; //from the included JS file. MyObj.CustomMethod(); //also from the included JS file. } catch(e)

我已经尝试了几天,研究如何在try/catch中创建自定义异常

以下是我试图做的:

我的html页面中包含了一个JS文件。JS文件定义了一个自定义对象,以及该对象的定义方法

接下来,在html页面中,我将执行以下操作:

try {
   MyObj = new CustomObj;     //from the included JS file.
   MyObj.CustomMethod();      //also from the included JS file.
} catch(e) {
   alert("Error in either the create of the object, or the method. Error is " + e.description)
}
我需要能够在CustomMethod()的代码中设置在catch语句中捕获的错误对象的属性。例如:

  CustomMethod = function{
     try{
       document.getelementById("field1").value = "my value";
     } catch(err) {
       //Set the return error
       ReturnErr.description = "There was an error!";
     }
  };
这能做到吗?根据我的尝试,我使用了throw语句,但它不会影响Error对象,因此catch部分永远不会被触发。在face中,自定义消息仅显示在控制台中

提前感谢。

试试:

function MyException(_message, _data) {
    this.message = _message;
    this.data = _data;
    this.name = "MyException";
}
用法



希望它能帮助您解决问题

可能重复的感谢。但我想我无法修改您示例中的(_error)@EricMeans,抱歉,输入错误,pass error作为第二个参数。抱歉,我的意思是不必在catch块中使用throw,而是在try块中调用的函数/方法中设置catch块得到的错误。这有什么意义吗?
try{
      //...                   
   }
   catch(_error){
      throw new MyException(message, _error);
   }