'How to throw an exception with a status code?

How can throw an error with options or a status code and then catch them?

From the syntax here, it seems we can through the error with additional info:

new Error(message, options)

So, can we throw like this below?

throw new Error('New error message', { statusCode: 404 })

Then, how can we catch that statusCode?

try {
 //...
} catch (e) {
  console.log(e.statusCode) // not working off course!
}

Any ideas?


Options are not supported yet.

Re-throw the error works:

try {
  const found = ...

  // Throw a 404 error if the page is not found.
  if (found === undefined) {
    throw new Error('Page not found')
  }

} catch (error) {
  // Re-throw the error with a status code.
  error.statusCode = 404
  throw error
}

but it is not an elegant solution.



Solution 1:[1]

You can use err.code

const error = new Error("message")
error.code = "YOUR_STATUS_CODE"
throw error;

Solution 2:[2]

as described here you have to create a custom exception for this:

function CustomException(message) {
  const error = new Error(message);

  error.code = "THIS_IS_A_CUSTOM_ERROR_CODE";
  return error;
}

CustomException.prototype = Object.create(Error.prototype);

then you can throw your custom exception:

throw new CustomException('Exception message');

Solution 3:[3]

based on response

const error = new Error(response?.error || 'error message here'); // error message
error.code = response?.code || 404; // you can custom insert your error code
error.name = "NOT FOUND"; // you can custom insert your error name
throw error;

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 Sandeep chand
Solution 2 Floxblah
Solution 3 Ismail Hosen