Technical note: As axios uses different libraries/mechanisms for Node and browser, this question touches only Node.js
usage of [email protected]
.
I can set up the following interceptor for the axios
library ( https://github.com/axios/axios#interceptors ):
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
//
// I am asking about this error handler and this error object
//
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
When the callback described in error handler for request interceptor is triggered and and what is the shape of that error object?
P.S. I see that there is this code describing work with errors in axios
:
axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
//
//
// !!!! This is a request error handler !!!
//
//
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
What will the error
inside the request error handler represent in the latter code?
I think this source code might help you:
createError.js
It looks like an instance of Error, so it has error.message
, and axios
adds error.config
, error.code
, error.request
and error.response
, per enhanceError.js.
When the callback described in error handler for request interceptor is triggered and and what is the shape of that error object?
the error handler (.catch clause) will be triggered by the interceptor, when it "rejects" a promise like in this part of your code:
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error); // <---- HERE
});
The shape of the axios error object is a JSON object as stated on the handling error section of axios docs on github
What will the error inside the request error handler represent in the latter code?
It will be the error response from the request bypassed by your axios interceptor
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