I want to write a common error handler which will catch custom errors thrown on purpose at any instance of the code.

When I did throw new Error('sample') like in the following code

try {
    throw new Error({'hehe':'haha'});
    // throw new Error('hehe');
} catch(e) {
    alert(e);
    console.log(e);
}

Log shows in Firefox as Error: [object Object] and I couldn’t parse the object.

For the second throw the log shows as: Error: hehe

Whereas when I did

try {
    throw ({'hehe':'haha'});
} catch(e) {
    alert(e);
    console.log(e);
}

the console showed as: Object { hehe="haha"} in which I was able to access the error properties.

What is the difference?

Is the difference as seen in the code? Like string will be just passed as string and object as objects but the syntax will be different?

I haven’t explored throwing error object… I had done only throwing strings.

Is there any other way than the above two mentioned methods?

12 s
12

throw “I’m Evil”

throw will terminate the further execution & expose message string on catch the error.

try {
  throw "I'm Evil"
  console.log("You'll never reach to me", 123465)
} catch (e) {
  console.log(e); // I'm Evil
}

Console after throw will never be reached cause of termination.


throw new Error(“I’m Evil”)

throw new Error exposes an error event with two params name & message. It also terminate further execution

try {
  throw new Error("I'm Evil")
  console.log("You'll never reach to me", 123465)
} catch (e) {
  console.log(e.name, e.message); // Error I'm Evil
}

throw Error(“I’m Evil”)

And just for completeness, this works also, though is not technically the correct way to do it –

try {
  throw Error("I'm Evil")
  console.log("You'll never reach to me", 123465)
} catch (e) {
  console.log(e.name, e.message); // Error I'm Evil
}

console.log(typeof(new Error("hello"))) // object
console.log(typeof(Error)) // function

Leave a Reply

Your email address will not be published. Required fields are marked *