[英]What is the shape of error object inside axios request interceptor error handler?
技術說明:由於 axios 對 Node 和瀏覽器使用不同的庫/機制,這個問題只涉及axios@0.18.0
Node.js
用法。
我可以為axios
庫( 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);
});
當請求攔截器的錯誤處理程序中描述的回調被觸發時,該錯誤對象的形狀是什么?
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);
});
會出現什么error
的請求錯誤處理程序中的代碼,后者代表什么呢?
我認為此源代碼可能對您有所幫助:
它看起來像Error 的一個實例,所以它有error.message
,並且axios
添加了error.config
、 error.code
、 error.request
和error.response
,每個enhanceError.js 。
當請求攔截器的錯誤處理程序中描述的回調被觸發時,該錯誤對象的形狀是什么?
錯誤處理程序(.catch 子句)將被攔截器觸發,當它“拒絕”像您代碼的這一部分那樣的承諾時:
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
});
axios 錯誤對象的形狀是 JSON 對象,如github 上 axios 文檔的處理錯誤部分所述
請求錯誤處理程序中的錯誤在后面的代碼中代表什么?
這將是您的 axios 攔截器繞過的請求的錯誤響應
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.