feat:登录注册完成
This commit is contained in:
34
src/utils/api-error.ts
Normal file
34
src/utils/api-error.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user