JoeTidee
JoeTidee

Reputation: 26044

Cannot get correct error from Axios

I have a doFetch function that handles all my api calls:

const doFetch = function(params){
    ...
    // Make request using Axios. Axios is promise based.
    return axios({
        method: method,
        url: baseUrl + url,
        data: queryParams,
        timeout: timeout,
        headers: {
            'Content-Type': contentType,
            'Authorization': `bearer ${Auth.getToken()}` // set the authorization HTTP header
        },
        responseType: responseType
    }).then((response) => {
        if(typeof params.callback === "function"){
            params.callback(response);
        }
        else {
            return response;
        }
    }).catch((err) => {
        if(typeof params.error === "function") {
            if (err.response) {
                params.error(err.response.data);
            }
        }
        else{
            if (err.response) {
                return err.response.data;
            }
            else{
                return err;
            }
        }
    });
};

One such api call is returning a custom error like so (express server):

return res.status(400).json("There was an error on the server.");

The function that calls doFetch is saveUser:

saveUser(userObj).then((response) => {                
    console.log("No Error");
}).catch((error) => {
    console.log("Error:", error);
});

The problem is that I am seeing No Error in the terminal, when I should only be expecting the error message to show. Any ideas?

Upvotes: 1

Views: 675

Answers (1)

num8er
num8er

Reputation: 19372

I like to return promise exactly, to be sure that it does/returns what I want.

I don't like to rely on "promise"-s of 3rd parties.


So I would recommend You to wrap it inside of promise and resolve/reject responses/errors manually:

const doFetch = params => {
    ...
    // Make request using Axios. Axios is promise based.
    return new Promise((resolve, reject) => {
      axios({
        method: method,
        url: baseUrl + url,
        data: queryParams,
        timeout: timeout,
        headers: {
            'Content-Type': contentType,
            'Authorization': `Bearer ${Auth.getToken()}` // set the authorization HTTP header
        },
        responseType: responseType
      })
      .then((response) => {
        console.info('doFetch:', response); // for debug purposes

        if(typeof params.callback === "function"){
          params.callback(response);
        }
        resolve(response);
      })
      .catch((err) => {
        console.error('doFetch:', err); // for debug purposes

        const error = (err.response) ? err.response.data : err;

        if(typeof params.error === "function") {
          params.error(error);
        }
        reject(error);
      });
    };
};

Upvotes: 1

Related Questions