Search code examples
javascriptexceptionthrow

how do you throw a custom error class in Javascript?


in JS, you can throw a "new Error(message)", but if you want to detect the type of the exception and do something different with the message, it is not so easy.

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

Is saying 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 does not work (get "undefined" and false)

Is this even possible?


Solution

  • 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 approach it should probably look like this :

    function MyError(message){
    
        var message = message;
        var name = "MyError";
        var poo = "poo";
    
        return{
    
            message: message, 
            name: name, 
            poo: poo
        }
    
    };