|
@@ -7,8 +7,8 @@ export type ResErrorHandler = <D, T extends ResData<D>>(response: AxiosResponse<
|
|
|
export type ReqErrorHandler = <T>(err: Error, response: AxiosRequestConfig<T>) => void
|
|
|
export type ResData<T> = { code: ResCode, message: string, data: T, msg: string }
|
|
|
export type Hook = {
|
|
|
- before: (config: AxiosRequestConfig) => void
|
|
|
- after: (config: AxiosRequestConfig) => void
|
|
|
+ before?: (config: AxiosRequestConfig) => void
|
|
|
+ after?: (config: AxiosRequestConfig) => void
|
|
|
}
|
|
|
|
|
|
export const axiosFactory = () => {
|
|
@@ -114,7 +114,7 @@ export const axiosFactory = () => {
|
|
|
}
|
|
|
|
|
|
const matchURL = (urls: string[], config: AxiosRequestConfig<any>) =>
|
|
|
- config.url && urls.includes(config.url)
|
|
|
+ config && config.url && urls.includes(config.url)
|
|
|
|
|
|
const callErrorHandler = (key: 'req' | 'res', ...args: any[]) => {
|
|
|
Promise.resolve()
|
|
@@ -127,16 +127,17 @@ export const axiosFactory = () => {
|
|
|
axiosRaw.interceptors.request.use(
|
|
|
config => {
|
|
|
for (const hook of axiosConfig.hook) {
|
|
|
- hook.before(config)
|
|
|
+ hook.before && hook.before(config)
|
|
|
}
|
|
|
|
|
|
if (!matchURL(axiosConfig.unTokenSet, config)) {
|
|
|
if (!axiosConfig.token) {
|
|
|
- // if (!matchURL(axiosConfig.unReqErrorSet, config)) {
|
|
|
- // const error = new Error('缺少token')
|
|
|
- // callErrorHandler('req', error, config)
|
|
|
- // throw error
|
|
|
- // }
|
|
|
+ if (!matchURL(axiosConfig.unReqErrorSet, config)) {
|
|
|
+ console.log(config.url)
|
|
|
+ const error = new Error('缺少token')
|
|
|
+ callErrorHandler('req', error, config)
|
|
|
+ throw error
|
|
|
+ }
|
|
|
} else {
|
|
|
config.headers = {
|
|
|
...config.headers,
|
|
@@ -151,7 +152,7 @@ export const axiosFactory = () => {
|
|
|
axiosRaw.interceptors.response.use(
|
|
|
(response: AxiosResponse<ResData<any>>) => {
|
|
|
for (const hook of axiosConfig.hook) {
|
|
|
- hook.after(response.config)
|
|
|
+ hook.after && hook.after(response.config)
|
|
|
}
|
|
|
|
|
|
if (matchURL(axiosConfig.unResErrorSet, response.config)) {
|
|
@@ -173,12 +174,12 @@ export const axiosFactory = () => {
|
|
|
},
|
|
|
(err) => {
|
|
|
for (const hook of axiosConfig.hook) {
|
|
|
- hook.after(err.config)
|
|
|
+ hook.after && hook.after(err.config)
|
|
|
}
|
|
|
if (!matchURL(axiosConfig.unResErrorSet, err.config)) {
|
|
|
callErrorHandler('res', err.response)
|
|
|
}
|
|
|
- throw new Error(err.response.statusText)
|
|
|
+ throw new Error(err.response && err.response.statusText)
|
|
|
}
|
|
|
)
|
|
|
|