使用 axios 的异步等待不返回错误
Async await with axios not returning errors
我在 axios 中使用异步等待,但在错误处理方面遇到了问题。使用正常的承诺(下面的示例 2),我可以在终止本地服务器时得到一个错误对象。但是,使用异步等待,error
未定义(下面的示例 1)有谁知道为什么会这样
const instance = axios.create({
baseURL: 'http://localhost:8000',
timeout: 3000,
})
// example 1
try {
await instance.get('/data/stores')
} catch (error) {
console.log(error) // error is not defined
}
// example 2
return instance.get('/data/stores').catch(error => {
console.log(error) // error is normal axios error
})
原来错误是在catch中,只是我的调试器没有识别出来。
错误响应存储在 response
属性 中。由于某些原因,您无法在 Chrome 的控制台中看到它。
所以在你的 catch 块中做:
console.log(error.response)
我在 axios 中使用异步等待,但在错误处理方面遇到了问题。使用正常的承诺(下面的示例 2),我可以在终止本地服务器时得到一个错误对象。但是,使用异步等待,error
未定义(下面的示例 1)有谁知道为什么会这样
const instance = axios.create({
baseURL: 'http://localhost:8000',
timeout: 3000,
})
// example 1
try {
await instance.get('/data/stores')
} catch (error) {
console.log(error) // error is not defined
}
// example 2
return instance.get('/data/stores').catch(error => {
console.log(error) // error is normal axios error
})
原来错误是在catch中,只是我的调试器没有识别出来。
错误响应存储在 response
属性 中。由于某些原因,您无法在 Chrome 的控制台中看到它。
所以在你的 catch 块中做:
console.log(error.response)