Reputation: 335
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);
});
};
Upvotes: 0
Views: 654
Reputation: 56
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
Upvotes: 0
Reputation: 241
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);
});
};
Upvotes: 0
Reputation: 111
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);
});
};
Upvotes: 3