0

I am making API call using axios in reactjs project but somehow I am not able to catch the error. I am getting 404 but not able to catch it. can somebody tell me what's wrong?

abc.js

export default axios.create({
  baseURL: `my_base_url`,
  headers: {
    "Content-Type": "application/json",
  },
});

xyz.js

export const createProcessApiCall = (param) => {
  return API.post("/v1/process1", param);
};

zzz.js

  const postData = async (param) => {
    await createProcessApiCall(param)
      .then((response) => {
          setApiData(response.data.data);
          setIsSuccess(response.data.isSuccess);    
      })
      .catch((e) => {
        setIsError(true);
      });
  };
1
  • Because it's not really an error. axios only raise error if the error is, let say, network error or such. 404 error, on the other hand, mean that the request was delivered. Read this question Commented Dec 23, 2020 at 12:57

3 Answers 3

3

you are combinining async code with sync code, try to use either asynchron :

   const postData = async (param) => {
    try {
       const result = await createProcessApiCall(param)
    }
    catch(err) {
         setIsError(true);
 
    }   
    };

Or synchron :

const postData = (param) => {
    createProcessApiCall(param)
      .then((response) => {
          setApiData(response.data.data);
          setIsSuccess(response.data.isSuccess);    
      })
      .catch((e) => {
        setIsError(true);
      });
  };
Sign up to request clarification or add additional context in comments.

Comments

0

Any status code different the sequence included between 200-299, you need to get at catch:

  const postData = async (param) => {
    await createProcessApiCall(param)
      .then((response) => {
          setApiData(response.data.data);
          setIsSuccess(response.data.isSuccess);    
      })
      .catch((e) => {
        // @TODO parse err
        console.log(e.response);
        setIsError(true);
      });
  };

Comments

0
axios.interceptors.response.use(res=>{return res}, (error) => {
 if (error.response.status !== 401) {
   throw error;
}

if (typeof error.response.data.error.name !== "undefined") {
   //do something on the error
}
});

its better to use axios interceptor to catch the error

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.