add axios serverResp error callback
This commit is contained in:
@@ -35,6 +35,7 @@ export * from "./utils/directives/Popup";
|
|||||||
export type { ScrollListener } from "./utils/Scroller";
|
export type { ScrollListener } from "./utils/Scroller";
|
||||||
export type { DraggableConfig } from "./utils/directives/Draggable";
|
export type { DraggableConfig } from "./utils/directives/Draggable";
|
||||||
export type { PopupConfig } from "./utils/directives/Popup";
|
export type { PopupConfig } from "./utils/directives/Popup";
|
||||||
|
export type { ErrorCallback } from "./utils/Network"
|
||||||
|
|
||||||
const install = function (app: App) {
|
const install = function (app: App) {
|
||||||
components.forEach(component => {
|
components.forEach(component => {
|
||||||
|
|||||||
@@ -1,20 +1,31 @@
|
|||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import { Response } from "~/types/Model";
|
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.defaults.withCredentials = true;
|
||||||
axios.interceptors.response.use((response: any) => {
|
axios.interceptors.response.use((axiosResp: any) => {
|
||||||
if (!response.config.responseType) {
|
if (!axiosResp.config.responseType) {
|
||||||
// 服务端返回
|
// 服务端返回
|
||||||
const data = response.data as Response;
|
const serverResp = axiosResp.data as Response;
|
||||||
if (data.code < 40000) {
|
if (serverResp.code < 40000) {
|
||||||
// 200 或 300 HTTP 状态段视为成功
|
// 200 或 300 HTTP 状态段视为成功
|
||||||
return data.data;
|
return serverResp.data;
|
||||||
} else {
|
} else {
|
||||||
|
if (globalErrorCallback) {
|
||||||
|
globalErrorCallback(serverResp);
|
||||||
|
}
|
||||||
// 由调用方处理
|
// 由调用方处理
|
||||||
return Promise.reject(data.msg);
|
return Promise.reject(serverResp.msg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return response.data;
|
return axiosResp.data;
|
||||||
}, (error: any) => {
|
}, (error: any) => {
|
||||||
// 请求错误
|
// 请求错误
|
||||||
if (error) {
|
if (error) {
|
||||||
@@ -34,4 +45,5 @@ axios.interceptors.response.use((response: any) => {
|
|||||||
|
|
||||||
export default {
|
export default {
|
||||||
axios,
|
axios,
|
||||||
|
setGlobalErrorCallback
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user