|
|
|
@ -2,54 +2,57 @@ import { notification } from 'antd'; |
|
|
|
|
import { AxiosError } from 'axios'; |
|
|
|
|
import { ApiResponse } from '../'; |
|
|
|
|
|
|
|
|
|
/** |
|
|
|
|
* 显示错误通知 |
|
|
|
|
*/ |
|
|
|
|
const showErrorNotification = (title: string, description: string) => { |
|
|
|
|
notification.error({ |
|
|
|
|
message: title, |
|
|
|
|
description, |
|
|
|
|
}); |
|
|
|
|
}; |
|
|
|
|
|
|
|
|
|
/** |
|
|
|
|
* 统一 API 请求拦截器,支持 useRequest.onError 正确捕获 |
|
|
|
|
*/ |
|
|
|
|
export const apiInterceptors = async <T = any, D = any, R = any>( |
|
|
|
|
promise: Promise<ApiResponse<T, D>>, |
|
|
|
|
): Promise<[null, T, R] | [Error, null, R]> => { |
|
|
|
|
): Promise<[null, T, R] | [Error, null, null]> => { |
|
|
|
|
try { |
|
|
|
|
const response = await promise; |
|
|
|
|
const { data } = response; |
|
|
|
|
|
|
|
|
|
if (!data.success) { |
|
|
|
|
const error = new Error(data.err_msg || '未知错误'); |
|
|
|
|
(error as any).code = data.err_code; |
|
|
|
|
(error as any).raw = data; |
|
|
|
|
notification.error({ |
|
|
|
|
message: '请求失败', |
|
|
|
|
description: data.err_msg || '接口异常,请重试', |
|
|
|
|
Object.assign(error, { |
|
|
|
|
code: data.err_code, |
|
|
|
|
raw: data, |
|
|
|
|
}); |
|
|
|
|
showErrorNotification('请求失败', data.err_msg || '接口异常,请重试'); |
|
|
|
|
return [error, null, null]; |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
return [null, data.data,response.data]; |
|
|
|
|
} catch (err: any) { |
|
|
|
|
return [null, data.data, response.data]; |
|
|
|
|
} catch (err) { |
|
|
|
|
let error: Error; |
|
|
|
|
let errMsg = '未知错误'; |
|
|
|
|
|
|
|
|
|
if (err.isAxiosError) { |
|
|
|
|
if (err instanceof AxiosError) { |
|
|
|
|
error = new Error('网络请求异常'); |
|
|
|
|
} else { |
|
|
|
|
error = err; |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
let errMsg = '接口异常'; |
|
|
|
|
if (err instanceof AxiosError && err.request.response) { |
|
|
|
|
try { |
|
|
|
|
const parsedResponse = JSON.parse(err.request.response); |
|
|
|
|
errMsg = parsedResponse?.err_msg ?? '接口异常'; |
|
|
|
|
} catch (parseError) { |
|
|
|
|
console.error('JSON 解析失败', parseError); |
|
|
|
|
if (err.request?.response) { |
|
|
|
|
try { |
|
|
|
|
const parsedResponse = JSON.parse(err.request.response); |
|
|
|
|
errMsg = parsedResponse.err_msg ?? '接口异常'; |
|
|
|
|
} catch (parseError) { |
|
|
|
|
console.error('JSON 解析失败', parseError); |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
} else { |
|
|
|
|
errMsg = err.message; |
|
|
|
|
error = err instanceof Error ? err : new Error('未知错误'); |
|
|
|
|
errMsg = error.message; |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
notification.error({ |
|
|
|
|
message: '请求异常', |
|
|
|
|
description: errMsg, |
|
|
|
|
}); |
|
|
|
|
|
|
|
|
|
return [error, null]; |
|
|
|
|
showErrorNotification('请求异常', errMsg); |
|
|
|
|
return [error, null, null]; |
|
|
|
|
} |
|
|
|
|
}; |
|
|
|
|
}; |