35 lines
977 B
TypeScript
35 lines
977 B
TypeScript
import type { ApiResponse } from '@/types/api'
|
|
|
|
export class ApiError extends Error {
|
|
code?: number
|
|
|
|
constructor(message: string, code?: number) {
|
|
super(message)
|
|
this.name = 'ApiError'
|
|
this.code = code
|
|
}
|
|
}
|
|
|
|
export function isApiSuccess(body: ApiResponse): boolean {
|
|
if (body.code === undefined) return true
|
|
return body.code === 200 || body.code === 0
|
|
}
|
|
|
|
export function unwrapApiData<T>(body: ApiResponse<T> & Record<string, unknown>): T {
|
|
if (body.data !== undefined && body.data !== null) {
|
|
return body.data as T
|
|
}
|
|
return body as T
|
|
}
|
|
|
|
export function getErrorMessage(err: unknown, fallback = '请求失败'): string {
|
|
if (err instanceof ApiError) return err.message
|
|
if (err instanceof Error && err.message) return err.message
|
|
if (err && typeof err === 'object' && 'data' in err) {
|
|
const data = (err as { data?: ApiResponse }).data
|
|
if (data?.msg) return data.msg
|
|
if (data?.message) return data.message
|
|
}
|
|
return fallback
|
|
}
|