Javascript – can you throw an object in an Error?

You can throw your own object, and associate an Error instance with it:

try {
  // ...
  throw {
    foo: "bar",
    error: new Error()
  };

The throw statement is not picky, but the Error() constructor is. Of course, if you throw something that’s not an Error, it’s only useful if the catching environment expects it to be whatever you throw.

Having the Error object as part of your custom thrown value is useful because a constructed Error instance has (in supporting browsers, which currently seems to be essentially all of them) an associated stack trace.

Leave a Comment