Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - can you throw an object in an Error?

Tags:

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); } 
like image 572
JoeTidee Avatar asked Jun 20 '18 18:06

JoeTidee


People also ask

Can you throw any object in JavaScript?

In JavaScript, all exceptions are simply objects. While the majority of exceptions are implementations of the global Error class, any old object can be thrown. With this in mind, there are two ways to throw an exception: directly via an Error object, and through a custom object.

What happens when an error is thrown in JavaScript?

The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack.

Does JavaScript have an error object?

When an error occurs, JavaScript will normally stop and generate an error message. The technical term for this is: JavaScript will throw an exception (throw an error). JavaScript will actually create an Error object with two properties: name and message.

What is error object in JavaScript?

The error object is a built-in object that provides a standard set of useful information when an error occurs, such as a stack trace and the error message. For example: Code: var error = new Error("The error message"); console. log(error); console.


2 Answers

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.

like image 125
Pointy Avatar answered Nov 27 '22 07:11

Pointy


You could try converting the object to a JSON string and then parsing the error message into a JSON object in the catch statement:

try {     throw Error(JSON.stringify({foo: 'bar'})); } catch (err) {     console.log(JSON.parse(err.message).foo); } 
like image 42
Keveloper Avatar answered Nov 27 '22 06:11

Keveloper