Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async await with axios not returning errors

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
})
like image 274
Matthew Chung Avatar asked Sep 06 '17 17:09

Matthew Chung


2 Answers

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)
like image 168
borislemke Avatar answered Nov 11 '22 09:11

borislemke


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

like image 45
Matthew Chung Avatar answered Nov 11 '22 08:11

Matthew Chung