I've developed a GoLang API and I'm attempting to consume it with Axios in my React application. When making API requests, Axios appears to only capture HTTP 200 responses, and I can't get any other error status codes. Here's my Axios API call from the React side:
axios.get('YOUR_API_ENDPOINT')
.then(response => {
console.log('Data:', response.data);
})
.catch(error => {
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
console.log(error.request);
} else {
console.log('Error', error.message);
}
});
On the GoLang server side, I'm sending responses using:
utils.FailureResp(w, http.StatusBadRequest, "No Data Found")
and
utils.ERROR(w, http.StatusInternalServerError, err)
However, within my React application, I'm only seeing results from the .then()
block, even when I'm certain the server is returning a non-200 status code.
Is there something I'm missing here? How can I correctly capture and handle non-200 HTTP responses sent from my GoLang API in my React application using Axios?
Given that my GoLang server is sending a non-200 status code using utils.FailureResp
and utils.ERROR
, I was expecting Axios in my React app to catch these error status codes in the catch block. Specifically, I expected to see the error response details, status code, and headers.
The issue here is the following: You are confusing HTTP status codes and their meaning with actual client side errors.
The
catch
onfetch
is for request errors: e.g there was no network available (you were offline), the connection dropped, or some request couldn't happen because of cors issue.Once the connection to the server has been established and an HTTP request was made and a replied managed to come back (no timeout errors) then that is a successful Request/Response HTTP interaction and it will be considered a success.
What you need to inspect instead is
Response.ok
: https://developer.mozilla.org/en-US/docs/Web/API/Response/okor
Response.status
:https://developer.mozilla.org/en-US/docs/Web/API/Response/status
LE: check out this link:https://developer.mozilla.org/en-US/docs/Web/API/fetch
In particular:
LE(2):
axios
seems to be different than plainfetch
so maybe this could help instead: https://github.com/axios/axios#handling-errors