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.
axios. defaults. headers. common = { "X-Requested-With": "XMLHttpRequest", "X-CSRFToken": "example-of-custom-header" };
Use the status property on the error. response object to get the status code from a HTTP error response, e.g. error. response.
axios. defaults. baseURL = 'https://api.example.com'; axios.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With