Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!