How do you produce your own error class in Javascript?

in JS you can throw a "new error (message)", but if you want to define the type of the exception and do something different with the message, it's not that easy.

This post: http://www.nczonline.net/blog/2009/03/10/the-art-of-throwing-javascript-errors-part-2/

Says you can do it something like this:

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

      

But it doesn't work (get "undefined" and "false")

Is it possible?

+3


source to share


1 answer


Douglas Crockford recommends throwing errors like this:

throw{

    name: "SomeErrorName", 
    message: "This is the error message", 
    poo: "this is poo?"

}

      

And then you can easily say:



try {
    throw{

        name: "SomeErrorName", 
        message: "This is the error message", 
        poo: "this is poo?"

    }

}
catch(e){
    //prints "this is poo?"
    console.log(e.poo)
}

      

If you really want to use the MyError Function method, it should look something like this:

function MyError(message){

    var message = message;
    var name = "MyError";
    var poo = "poo";

    return{

        message: message, 
        name: name, 
        poo: poo
    }

};

      

+1


source







All Articles