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.