ewm76903
ewm76903

Reputation: 11

Javascript Custom Exception

I have tried for a couple of days researching on how to create a custom exception in a try/catch.

Here is what I am attempting to do:

I have an included JS file in my html page. The JS file defines a custom object, as well as defining methods for the object.

Next, in the html page I am doing the following:

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

I need to be able, within the code for the CustomMethod(), to set the Error Object's properties that are captured in the catch statement. For example:

  CustomMethod = function{
     try{
       document.getelementById("field1").value = "my value";
     } catch(err) {
       //Set the return error
       ReturnErr.description = "There was an error!";
     }
  };

Can this be done? From what I have tried, I have used the throw statement, but it does not effect the Error Object, thus the catch section is never triggered. In face, the custom message is only shown in the Console.

Thanks ahead of time.

Upvotes: 1

Views: 1178

Answers (1)

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

Try:

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

Usage

try{
      //...                   
   }
   catch(_error){
      throw new MyException(message, _error);
   }

Hope it will help you to sort things out

Upvotes: 2

Related Questions