refactor: ky

This commit is contained in:
skytek_xinliang
2026-05-07 11:17:30 +08:00
parent 87fbc1dda8
commit 71683482e1
15 changed files with 146 additions and 360 deletions
+11 -13
View File
@@ -1,5 +1,5 @@
import type { ApiError } from '@/types/api'
import { isAxiosError } from 'axios'
import { isHTTPError, isTimeoutError } from 'ky'
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
@@ -51,12 +51,6 @@ export function extractErrorMessage(data: unknown): string | undefined {
return firstString(data)
}
// 統一錯誤格式
//
// 設計重點:
// - 將 AxiosError 與非預期錯誤統一轉成 ApiRequestError
// - Store 只需要處理 message/code/status,不需理解 Axios 結構
// - 取消請求(AbortController)會轉成 CanceledRequestError
export class ApiRequestError extends Error {
code?: number
status?: number
@@ -87,9 +81,6 @@ export class CanceledRequestError extends ApiRequestError {
}
export function isRequestCanceled(error: unknown): boolean {
if (isAxiosError(error)) {
return error.code === 'ERR_CANCELED'
}
return error instanceof DOMException && error.name === 'AbortError'
}
@@ -102,9 +93,9 @@ export function normalizeError(error: unknown): ApiRequestError {
return new CanceledRequestError()
}
if (isAxiosError(error)) {
const status = error.response?.status
const data = error.response?.data as unknown
if (isHTTPError(error)) {
const status = error.response.status
const data = error.data
const message = extractErrorMessage(data) || error.message || '請求失敗'
const apiError = isRecord(data) ? (data as Partial<ApiError>) : undefined
const code = apiError?.code ?? status
@@ -117,6 +108,13 @@ export function normalizeError(error: unknown): ApiRequestError {
})
}
if (isTimeoutError(error)) {
return new ApiRequestError({
message: '請求逾時',
raw: error,
})
}
if (error instanceof Error) {
return new ApiRequestError({ message: error.message, raw: error })
}