diff --git a/src/index.ts b/src/index.ts index aae2fc8..1aa32f5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -35,6 +35,7 @@ export * from "./utils/directives/Popup"; export type { ScrollListener } from "./utils/Scroller"; export type { DraggableConfig } from "./utils/directives/Draggable"; export type { PopupConfig } from "./utils/directives/Popup"; +export type { ErrorCallback } from "./utils/Network" const install = function (app: App) { components.forEach(component => { diff --git a/src/utils/Network.ts b/src/utils/Network.ts index 537385a..6c02146 100644 --- a/src/utils/Network.ts +++ b/src/utils/Network.ts @@ -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 };