How to capture Axios error Response data when user has no connection?

Asked

Viewed 675 times

2

I am using the Third Party of axios to handle errors in requests.

I am currently using this way:

const api = axios.create({
  baseURL: 'http://localhost:3333'
});

api.interceptors.response.use(
  function (response) {
    // Qualquer status code que for entre o range 2xx ativa essa trigger
    // Mostra o toastr de success com mensagem vinda do backend
    ...
  }, function (error) {
    // Qualquer status code que for fora do range 2xx ativa essa trigger
    // Mostra o toastr de erro com mensagem vinda do backend
    ...
  }

As you can see, when an error occurs in my backend, it enters the error and I can capture the error data and show a accessing toastr error.response.data. But how can I capture error data when user has no connection?

I tried to:

console.log(error)

Is printado:
inserir a descrição da imagem aqui

Is it possible to access only this error message? "Network Error" or something similar to this error?

I tried too:

console.log(error.response) // printa undefined
  • Just try it with console.log(error).

1 answer

0


After researching for a while, I found this Issue on the Axios github where the same question was asked.

As stated in the replies, it is impossible to detect network errors in the browser, so Axios responds with a generic error message

"Error: Network Error"

Where it does not have a specific status, therefore, it was enough to do the following check:

if (!error.status) {
    // Usuário não possui internet, mostra toastr de erro
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.