add axios serverResp error callback
This commit is contained in:
@@ -1,20 +1,31 @@
|
||||
import axios from "axios";
|
||||
import { Response } from "~/types/Model";
|
||||
|
||||
export type ErrorCallback = (response: Response) => void;
|
||||
|
||||
let globalErrorCallback: ErrorCallback | null = null;
|
||||
|
||||
export const setGlobalErrorCallback = (callback: ErrorCallback) => {
|
||||
globalErrorCallback = callback;
|
||||
};
|
||||
|
||||
axios.defaults.withCredentials = true;
|
||||
axios.interceptors.response.use((response: any) => {
|
||||
if (!response.config.responseType) {
|
||||
axios.interceptors.response.use((axiosResp: any) => {
|
||||
if (!axiosResp.config.responseType) {
|
||||
// 服务端返回
|
||||
const data = response.data as Response;
|
||||
if (data.code < 40000) {
|
||||
const serverResp = axiosResp.data as Response;
|
||||
if (serverResp.code < 40000) {
|
||||
// 200 或 300 HTTP 状态段视为成功
|
||||
return data.data;
|
||||
return serverResp.data;
|
||||
} else {
|
||||
if (globalErrorCallback) {
|
||||
globalErrorCallback(serverResp);
|
||||
}
|
||||
// 由调用方处理
|
||||
return Promise.reject(data.msg);
|
||||
return Promise.reject(serverResp.msg);
|
||||
}
|
||||
}
|
||||
return response.data;
|
||||
return axiosResp.data;
|
||||
}, (error: any) => {
|
||||
// 请求错误
|
||||
if (error) {
|
||||
@@ -34,4 +45,5 @@ axios.interceptors.response.use((response: any) => {
|
||||
|
||||
export default {
|
||||
axios,
|
||||
setGlobalErrorCallback
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user