异步等待axios不返回错误

Mat*_*ung 9 javascript async-await axios

我正在使用异步等待axios并且我遇到了错误处理问题.使用正常的promise(下面的例子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
})
Run Code Online (Sandbox Code Playgroud)

bor*_*mke 11

错误响应存储在response属性中.出于某种原因,您无法在Chrome的控制台中看到这一点.

所以在你的catch块中做:

console.log(error.response)
Run Code Online (Sandbox Code Playgroud)


Mat*_*ung 8

事实证明错误存在于catch中,只是我的调试器无法识别它.