异步等待axios不返回错误

时间:2017-09-06 17:28:32

标签: javascript async-await axios

我正在使用asios等待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
})

2 个答案:

答案 0 :(得分:9)

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

所以在你的catch块中:

console.log(error.response)

答案 1 :(得分:8)

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