社區(qū)精選|“奇怪”的 Axios 攔截器
今天小編為大家?guī)淼氖巧鐓^(qū)作者 Ruofee 的文章,讓我們一起來學習 “奇怪”的 axios 攔截器。
事情經(jīng)過
{
code: 200, // 200 表示接口返回正常,非 200 則為異常
data: {}, // 返回的數(shù)據(jù)
message: '', // 接口報錯時的錯誤信息
}
當 code 字段為 200 時,則表示接口正常,這時候我們正常取數(shù)據(jù)就行;
當 code 為非 200 時,表示接口異常,此時我們需要把對應的錯誤信息進行彈窗報錯;
這屬于一個通用的處理,因此我們可以利用 axios 返回攔截器進行處理:
{
import axios from 'axios';
const handleRes = config => {
if (config.data.code !== 200) {
throw config;
}
return config;
};
const handleErr = error => {
// 把錯誤信息進行彈窗
};
axios.interceptors.response.use(handleRes, handleErr);
}
=.= 這就是我的直覺寫法,handleRes 函數(shù)對響應體進行處理,對返回數(shù)據(jù)的 code 進行判斷,如果不為 200 則拋出一個錯誤,并由 handleErr 函數(shù)捕獲,然后再進行彈窗處理。
終究還是出問題了
想法很美好,但其實 handleErr 是不生效的……
貼個官網(wǎng)的示例:
{
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
只要狀態(tài)碼超過 2xx 便會觸發(fā)這個函數(shù)
也就是說,它只會在請求異常時觸發(fā),也就是接口 http code 不為 2xx 時。
發(fā)現(xiàn)原因
解決問題,首先要研究源碼 =.=
{
const responseInterceptorChain = [];
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
});
// ...省略一大段代碼
try {
promise = dispatchRequest.call(this, newConfig);
} catch (error) {
return Promise.reject(error);
}
i = 0;
len = responseInterceptorChain.length;
while (i < len) {
promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
}
可以看出攔截器中的參數(shù)最終會作為 Promise.prototype.then 的參數(shù),也就是說我們的代碼可以等同于:
promise.then(handleRes, handleErr);
而 handleErr 函數(shù)只捕獲 promise 變量的錯誤,不捕獲 handleRes 函數(shù)中的錯誤,如果需要捕獲,應該在后面使用 catch 或是 then 函數(shù):
promise.then(handleRes, handleErr).catch(err => {});
promise.then(handleRes, handleErr).then(undefined, err => {});
換成攔截器的語法,也就是再新增一個響應攔截器,定義一個錯誤捕獲函數(shù):
import axios from 'axios';
const handleRes = config => {
if (config.data.code !== 200) {
throw config;
}
return config;
};
const handleErr = error => {
// 把錯誤信息進行彈窗
};
axios.interceptors.response.use(handleRes);
axios.interceptors.response.use(undefined, handleErr);
后續(xù)
往期推薦
社區(qū)精選|大廠前端架構(gòu)實戰(zhàn)之 modal 模態(tài)對話框管理
社區(qū)精選|深度剖析 Vite 配置文件
社區(qū)精選|使用CSS Paint API實現(xiàn)有趣的圖像碎片效果
評論
圖片
表情
