最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Async await with axios not returning errors - Stack Overflow

programmeradmin2浏览0评论

I'm using async await with axios and am having trouble with the error handling. Using normal promises (example 2 below), I can get an error object when killing my local server. However, using async await, the error comes in as undefined (example 1 below) Does anyone know why this would be

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
})

I'm using async await with axios and am having trouble with the error handling. Using normal promises (example 2 below), I can get an error object when killing my local server. However, using async await, the error comes in as undefined (example 1 below) Does anyone know why this would be

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
})
Share Improve this question asked Sep 6, 2017 at 17:28 Matthew ChungMatthew Chung 1,3421 gold badge19 silver badges31 bronze badges 1
  • Had exactly the same trouble with firefox and chrome – opensas Commented Jul 20, 2018 at 7:07
Add a comment  | 

2 Answers 2

Reset to default 17

The error response is stored inside response property. For some reason you can't see this in Chrome's console.

So in your catch block do:

console.log(error.response)

It turns out the error was there within the catch, it is just that my debugger did not recognize it.

发布评论

评论列表(0)

  1. 暂无评论