Skip to content
Advertisement

What is the difference between throw Error(error) and throw error

What is the difference between:

try {
      const result = await hello();
    } catch (error) {
      throw error;
    }

and

try {
      const result = await hello();
    } catch (error) {
      throw Error(error);
    }

Also

Is the second one necessary? It seems like you are just wrapping an error with an Error Object. Which one is preferred? Please help me understand.

Answer

It’s possible that the value that the Promise rejected with was not an error object, but something else:

(async() => {
  try {
    const result = await Promise.reject(5);
  } catch (error) {
    console.log(error);
    console.log(typeof error);
  }
})();

Doing

throw Error(error);

makes sure that the value being thrown is definitely an Error object, which could be important if the thrown value is examined later and is expected to be such an object. You wouldn’t want, for example, for undefined or null to be thrown (strange, I know, but not impossible) and for accessing a property of that to then throw at the point where you’re catching for real.

const hello = () => new Promise((resolve, reject) => {
  reject();
});
(async() => {
  try {
    const result = await hello();
  } catch (error) {
    throw error;
  }
})()
  .catch((error) => {
    console.log('The error message was:');
    console.log(error.message);
  });
Advertisement