Axios in React not capturing non-200 HTTP responses from GoLang API

72 Views Asked by At

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.

1

There are 1 best solutions below

1
On

The issue here is the following: You are confusing HTTP status codes and their meaning with actual client side errors.

The catch on fetch 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/ok

or 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:

A fetch() promise only rejects when a network error is encountered (which is usually when there's a permissions issue or similar). A fetch() promise does not reject on HTTP errors (404, etc.). Instead, a then() handler must check the Response.ok and/or Response.status properties.

LE(2): axios seems to be different than plain fetch so maybe this could help instead: https://github.com/axios/axios#handling-errors