Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 886
Gregg Avatar asked Oct 13 '16 18:10

Gregg


People also ask

How do I set global headers in Axios?

axios. defaults. headers. common = { "X-Requested-With": "XMLHttpRequest", "X-CSRFToken": "example-of-custom-header" };

How do I get error codes from Axios?

Use the status property on the error. response object to get the status code from a HTTP error response, e.g. error. response.

What is Axios default baseURL?

axios. defaults. baseURL = 'https://api.example.com'; axios.

Does Axios throw errors?

By default, the axios HTTP library throws an error anytime the destination server responds with a 4XX / 5XX error (for example, a 400 Bad Request ). Since axios raises an error, your workflow will stop at this step. See the axios docs for more information.


2 Answers

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.

like image 40
link Avatar answered Sep 29 '22 09:09

link


You can use response interceptors as documents in axios documentation.

axios.interceptors.response.use(undefined, function (error) {
    if(error.response.status === 401) {
      ipcRenderer.send('response-unauthenticated');
      return Promise.reject(error);
    }
  });

other thread with same discussion

like image 181
prasann shah Avatar answered Sep 29 '22 09:09

prasann shah