我正在开发一个在异步等待函数中使用axios发出请求的网站,该函数如下所示:
async function () {
try {
const response = await axios.get('requestUrl')
} catch (e) {
throw new Error(e)
}
}一切正常,但我不知道如何处理具有特定状态的错误(例如,当响应状态为400时显示特定消息)。我尝试过使用e.status,但它不起作用,因此,我不知道调用什么才能获得请求的状态。我也尝试了使用response.status的try函数,我知道它会以400的状态响应,但它也不起作用。当response.status为200时,它就能工作了。
发布于 2018-09-18 20:22:15
使用error.response.status
async function () {
try {
const response = await axios.get('requestUrl')
} catch (e) {
if (e.response.status === 400) {
// ...
} else {
// ...
}
}
}发布于 2022-08-27 04:18:35
用typescript编写的代码
try {
const response = await axios.get('requestUrl')
}
catch (e) {
const axiosErr = e as AxiosError
const status = axiosErr.response ? axiosErr.response.status : 0
if (status === 400) {
// ...
} else {
// ...
}
}https://stackoverflow.com/questions/52394015
复制相似问题