如何构建一个 Error 对象而不是给它一个字符串? https://codesandbox.io/s/pwr973487x
async function getUrl() {
try {
const res = await axios.get('https://httpstat.us/500')
} catch(e) {
const errorObj = {
status: 500,
message: 'Internal server error, something is not defined etc'
}
throw new Error('err') //how to build object?
}
}
我希望 throw Error()
返回 errorObj
。我是否必须创建自己的类才能做到这一点,或者我可以为此修改现有的 Error 类吗?我需要它,以便它标准化我的不同 API 集的错误消息。
最佳答案
您可以使用catch返回的错误对象
try {
const res = await axios.get('https://httpstat.us/500')
} catch(e) {
e.message = 'Internal server error, something is not defined etc';
throw e;
}
关于javascript - 抛出对象而不是返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50326002/