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.
options
should look like. It can include acause
. – SayreError
specifically and not anything else? – Sayrethrow Object.assign(new Error('New error message'), { statusCode: 404 });
– Eparchytry
/catch
as control flow. Because there is no control, it's linear. Why not create the error, add the property then throw it, instead of create -> throw -> add property -> rethrow? I do not understand what you want to happen here. What solution exactly are you looking for, why the roundaboundness of this all? – Sayreoptions
is for: It's not for passing arbitrary key/value pairs likestatus: "404"
, it's for passingcause: "<something>"
. Regardless of support, you can't use it to pass arbitrary data around with your exceptions. You have two answers below that will allow you to do this, and you've rejected them both, one because you want it "shorter" and one because you don't want to use custom errors for some reason. Please clarify your requirements. – Zoooptions
parameter. – Zoo