Is there any way to set axios global configuration for error response codes

I use axios in my response / redux application, and when I get errors like 401, 404, etc. I have to deal with them for every action function when I make calls in axios. I have axios_config.js where I wrapped 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 afraid, these are common mistakes like 401, 404, etc. I am currently 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 I don't want to deal with 401, 404, etc. everytime. Therefore, I need to deal with those who work on a more global scale, but are still able to handle certain errors for the request, for example, server-side validation errors.

+7
reactjs redux axios react-redux
source share
2 answers

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

This can then be transferred to a single file, and you can always change 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.

+1
source share

You can use response interceptors as documents in the axiom documentation.

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

another thread with the same discussion

+11
source share

All Articles