import axios, { AxiosRequestConfig, AxiosResponse } from 'axios' import { APIError, HttpError, PlainObject } from './errors' // 全局接口报错提示设置 let notification = (msg: string) => { alert(msg) } // 接口域名 const host = '' export function setNotification(fun: (msg: string) => void) { notification = fun } export function getNotification() { return notification } export interface AxOptions extends AxiosRequestConfig { hideError?: boolean } // 同一个错误提示,5 秒内只出一次 let notificationQueue: PlainObject = {} // 处理错误 export function handleError(err: any, hideErr = false) { const response = err.response as AxiosResponse // 如果是手动取消的请求,不显示错误信息 if (axios.isCancel(err)) { console.warn(err) } else { if (!hideErr) { if (response) { const code = response.status switch (code) { case 403: location.hash = '#/login' throw new APIError('请登录', response) } } let message: string = err.message if (message.includes('Network Error')) { message = '网络连接错误,请稍后再试' } if (!notificationQueue[message]) { notificationQueue[message] = true setTimeout(() => (notificationQueue[message] = false), 5000) notification(message) } } else { console.warn(err) } throw err } } export let ax = axios.create({ baseURL: host, timeout: 30000, responseType: 'json' }) ax.interceptors.request.use(async options => { return options }) ax.interceptors.response.use(res => { if (res) { return res } else { throw new HttpError('网络连接错误,请稍后再试', res) } })