lau*_*kok 38 javascript error-handling try-catch throw
如何抛出带有选项或状态代码的错误然后捕获它们?
从这里的语法来看,我们似乎可以通过附加信息来解决错误:
new Error(message, options)
Run Code Online (Sandbox Code Playgroud)
那么,我们可以像下面这样抛出吗?
throw new Error('New error message', { statusCode: 404 })
Run Code Online (Sandbox Code Playgroud)
那么,我们怎样才能抓住它呢statusCode?
try {
//...
} catch (e) {
console.log(e.statusCode) // not working off course!
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
尚不支持选项。
重新抛出错误即可:
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
}
Run Code Online (Sandbox Code Playgroud)
但这不是一个优雅的解决方案。
小智 41
您可以使用 err.code
const error = new Error("message")
error.code = "YOUR_STATUS_CODE"
throw error;
Run Code Online (Sandbox Code Playgroud)
小智 9
如此处所述,您必须为此创建一个自定义异常:
function CustomException(message) {
const error = new Error(message);
error.code = "THIS_IS_A_CUSTOM_ERROR_CODE";
return error;
}
CustomException.prototype = Object.create(Error.prototype);
Run Code Online (Sandbox Code Playgroud)
然后你可以抛出你的自定义异常:
throw new CustomException('Exception message');
Run Code Online (Sandbox Code Playgroud)