add Network.globalErrorCallback

This commit is contained in:
Timi
2025-12-03 11:53:10 +08:00
parent 53f100cb4e
commit a5b51b3492
2 changed files with 23 additions and 8 deletions

View File

@ -56,7 +56,9 @@ const install = function (app: App) {
app.use(component as unknown as { install: () => any });
});
};
const axios = Network.axios;
const setGlobalErrorCallback = Network.setGlobalErrorCallback;
export default {
install
@ -65,6 +67,7 @@ export default {
export {
axios,
Network,
setGlobalErrorCallback,
UserAPI,
CommonAPI,

View File

@ -2,6 +2,14 @@ import axios, { InternalAxiosRequestConfig } from "axios";
import { Response } from "~/types/Model";
import { Cooker, Time, userStore } from "~/index";
type ErrorCallback = (response: Response) => void;
let globalErrorCallback: ErrorCallback | null = null;
export const setGlobalErrorCallback = (callback: ErrorCallback) => {
globalErrorCallback = callback;
};
const userTokenInterceptors = async (config: InternalAxiosRequestConfig<any>) => {
let token = userStore.loginUser.token?.value;
const cookieToken = Cooker.get("Token");
@ -25,19 +33,22 @@ const userTokenInterceptors = async (config: InternalAxiosRequestConfig<any>) =>
return config;
};
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) {
@ -57,5 +68,6 @@ axios.interceptors.response.use((response: any) => {
export default {
axios,
userTokenInterceptors
userTokenInterceptors,
setGlobalErrorCallback
};