Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

240
Visualizações
Avoid handling if error has response in Vue with Axios in every request

I use the axios interceptors to handle some errors, specially the errors without response. And in some parts of my project, I use the message contained in the error.response.data for validations and showing a messaged stored in the backend. But this interceptor is not preventing me from having to check if the error has a response.

My interceptor:

axios.interceptors.response.use(
    function (response) {
      ...
    },
    function (error) {
      if (!error.response) {
        ...
        return Promise.reject(new Error(error.message))
      }

An example of a request that depends on having the error.response:

this.$store.dispatch('updateField', { [this.fieldKey]: this.value ? this.value : null }).catch((error) => {
        this.validateField(error.response.data)
      })

But I'd have to put the validateField call inside an if(eror.response) to avoid an error in the console, and spread this if all over my code?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

response can be treated as optional, because it actually is:

this.validateField(error.response?.data)

Or normalized error that contains needed properties and doesn't rely on the structure of Axios error can be created in an interceptor:

function (rawError) {
  const error = new Error(error.response?.data?.myError || error.message);
  error.data = error.response?.data || null;
  error.headers = error.response?.headers || null;
  error.status = error.response?.status || 0;
  return Promise.reject(error);
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda