4

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?

1 Answer 1

5

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
    }

};
Sign up to request clarification or add additional context in comments.

2 Comments

Brilliant. the throw of a direct object seems to work. The only issue I read is that browsers dont handle it so well. Whats the difference between my MyError and your MyError? Im guessing its the scoping. yours has no this, so is kind of private.
In your MyError function all the variables are scoped within that object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.