(error: ErrorLike, fallbackTitle = '操作失败')
| 14 | export type ErrorLike = AppError | string | Error | unknown |
| 15 | |
| 16 | export function normalizeApiError(error: ErrorLike, fallbackTitle = '操作失败'): AppError { |
| 17 | if (isAppError(error)) return error |
| 18 | |
| 19 | if (axios.isAxiosError(error)) { |
| 20 | const data = error.response?.data |
| 21 | if (isAppError(data?.error)) return data.error |
| 22 | if (typeof data?.error === 'string') { |
| 23 | return legacyMessageToError(data.error, data.error_message || fallbackTitle, error.response?.status) |
| 24 | } |
| 25 | if (typeof data?.error_message === 'string') { |
| 26 | return legacyMessageToError(data.error_message, fallbackTitle, error.response?.status) |
| 27 | } |
| 28 | if (!error.response) { |
| 29 | return legacyMessageToError( |
| 30 | error.message || '网络连接失败', |
| 31 | '网络连接失败', |
| 32 | 0, |
| 33 | '请确认后端服务已启动,并检查浏览器网络连接。' |
| 34 | ) |
| 35 | } |
| 36 | return legacyMessageToError(error.message, fallbackTitle, error.response.status) |
| 37 | } |
| 38 | |
| 39 | const maybeData = error as any |
| 40 | if (isAppError(maybeData?.error)) return maybeData.error |
| 41 | if (typeof maybeData?.error === 'string') { |
| 42 | return legacyMessageToError(maybeData.error, maybeData.error_message || fallbackTitle, maybeData.status) |
| 43 | } |
| 44 | if (typeof maybeData?.message === 'string') { |
| 45 | return legacyMessageToError(maybeData.message, fallbackTitle, maybeData.status) |
| 46 | } |
| 47 | if (typeof error === 'string') { |
| 48 | return legacyMessageToError(error, fallbackTitle) |
| 49 | } |
| 50 | |
| 51 | return legacyMessageToError('请稍后重试;如果持续失败,请复制诊断信息反馈。', fallbackTitle) |
| 52 | } |
| 53 | |
| 54 | export function formatErrorMessage(error: ErrorLike, fallbackTitle = '操作失败'): string { |
| 55 | const appError = normalizeApiError(error, fallbackTitle) |
no test coverage detected