Gregg Gregg - 1 month ago 26
React JSX Question

Is there a way to set global axios config for error response codes

I'm using

axios
in my react/redux application and when I get errors like 401, 404, etc I currently have to deal with them for each action function when I make the calls to axios. I have a axios_config.js where I've wrapped the axios calls with some common idioms. For example:

// need to move this to app config
const BASE_URL = 'http://localhost:8080/api/';

function config() {
return {
headers: {'X-Token-Auth': localStorage.getItem('token')}
}
}

export function fetchData(url) {
return axios.get(`${BASE_URL}${url}`, config());
};


Where I'm struggling are the common errors like 401, 404, etc. Currently, I'm doing this:

export function fetchBrands() {
return function(dispatch) {
dispatch({type:FETCHING_BRANDS});

fetchData('brands')
.then(response => {
dispatch({
type: FETCH_BRANDS_SUCCESS,
payload: response
});
})
.catch(err => {
// deal with errors
});
}
}


But in the
catch
block, I don't want to have to deal with 401, 404 etc every single time. So I need to be able to deal with those on a more global scale but still have the ability to handle specific errors to the request like server side validation errors for example.

Answer

You can try to write a function that accepts a function and returns the function with a catch attached. You can even pass an optional secondary argument to execute local catch logic.

This could then be moved to a single file and you can always modify it there.

export function fetchBrand(id) {
  return function (dispatch) {
    wrapCatch(
      fetchData(`brands/${id}`)
        .then(response => {
          dispatch({
            type: FETCH_BRAND_SUCCESS,
            payload: response
          });
        }),
      function (err) {
        // deal with errors
      }
    );
  }
}
  
export function wrapCatch(f, localErrors) {
  return f.catch(err => {
      // deal with errors
      localErrors();
  });
}

Hope this helps.