From a5b51b34929fc61073837dbb8becc74a35c2e640 Mon Sep 17 00:00:00 2001 From: Timi Date: Wed, 3 Dec 2025 11:53:10 +0800 Subject: [PATCH] add Network.globalErrorCallback --- src/index.ts | 3 +++ src/utils/Network.ts | 28 ++++++++++++++++++++-------- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/src/index.ts b/src/index.ts index 87898c3..a614653 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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, diff --git a/src/utils/Network.ts b/src/utils/Network.ts index 4efa410..8d9ae03 100644 --- a/src/utils/Network.ts +++ b/src/utils/Network.ts @@ -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) => { let token = userStore.loginUser.token?.value; const cookieToken = Cooker.get("Token"); @@ -25,19 +33,22 @@ const userTokenInterceptors = async (config: InternalAxiosRequestConfig) => 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 };