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

146
Visualizações
Good practice handling Axios errors in React

I have a doubt about handling API call errors using Axios. This is working for me but it seems I am using too much logic inside the Catch error Callback.

const onSubmit = async (data) => {
    
    await axios
      .post("http://localhost:3001/auth/verify-email", data, {
        headers: {
          "Content-Type": "application/json",
        },
      })
      .then((res) =>
        navigate("/", {
          state: {
            response: res.data.result,
            verified: true,
            message: "You have succesfully registered",
          },
        })
      )
      .catch((error) => {
        if (error.response.data.errors[0].code === "InvalidToken") {
          axios.get(`http://localhost:5001/auth/verify-email/${data.email}`);
          alert("Check your email for the new Verification Code");
          navigate("/authentication", {
            state: { email: data.email },
          });
        }
      });
  };

In this case if one sort of error happens, then it calls an API to reset the token. It works fine but maybe it can be refactored.

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

0

Check axios doc on errors

If you want to extract the error code in a "cleaner" way, you can treat it this way : error.toJSON()

This way your logic to catch the error will be less "messy"

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