Friday, May 10, 2024
73
rated 0 times [  74] [ 1]  / answers: 1 / hits: 25150  / 6 Years ago, wed, june 20, 2018, 12:00:00

Is it possible to throw an object using Error? In the example below the console shows undefined.


try {
throw Error({foo: 'bar'});
} catch (err) {
console.log(err.message.foo);
}

More From » error-handling

 Answers
4

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.


[#54158] Sunday, June 17, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
julieth

Total Points: 382
Total Questions: 99
Total Answers: 85

Location: Cape Verde
Member since Fri, Nov 27, 2020
4 Years ago
;