'Javascript - can you throw an object in an Error?

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);
}


Solution 1:[1]

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);
}

Solution 2:[2]

For anyone using , you can extend the ErrorConstructor interface and add your own constructor that accepts an object like this:

class MyError extends Error {
  readonly id: number

  // base constructor only accepts string message as an argument
  // we extend it here to accept an object, allowing us to pass other data
  constructor({ id, name, message }) {
    super(message)
    this.name = name // this property is defined in parent
    this.id = id
  }
}

Usage

function doSomething() {
  if (somethingWentWrong) {
    throw new MyError({
      id: 502,
      name: "throttle_violation",
      message: "Violation of backoff parameter",
    });
  }
}

try {
  doSomething()
} catch (err) {
  if (err instanceof MyError) {
    console.log("error id: " + err.id);
    console.log("error name: " + err.name);
    console.log("error message: " + err.message);
    alert(err.property); // name
  } else {
    // ...
  }
}

Solution 3:[3]

Using JSON.stringify() and JSON.parse() can be a pain and isn't necessary even. I'd suggest creating your own property for the Error object, rather than passing the object to the message parameter, which only accepts a string.

try {
  let error = new Error();
    
  Object.assign(error, { foo: 'bar' });

  throw error;
} catch (err) {
  console.log(err.foo);
}

Solution 4:[4]

you could try with the cause propoty of :

TS has inaccurate value type about it at present, this is being discussed on the official to revolve it.

try {
     throw new Error('Failed in some way', { 
       cause: {foo: 'bar'} 
     });
} catch(e) {
     console.log(e); // Error('Failed in some way')
     console.log(e.cause) // {foo: 'bar'}
}

or throw the Error instance with the custom property

try {
     const error = new Error('Failed in some way');
     error.foo = 'bar';
     throw error;
   } catch(e) {
     console.log(e); // Error('Failed in some way')
     console.log(e.foo) // 'bar'
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Keveloper
Solution 2
Solution 3
Solution 4