Browse Source

feat: add ApiError class to preserve error data through unwrapApiBody

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
feat/registration-page
npmrun 2 weeks ago
parent
commit
9ca4608fe0
  1. 9
      app/utils/http/factory.ts

9
app/utils/http/factory.ts

@ -7,13 +7,20 @@ export type ApiResponse<T = unknown> = {
data: T data: T
} }
/** Wraps API error responses, preserving the data field for field-level error handling */
export class ApiError extends Error {
constructor(message: string, public data: unknown) {
super(message)
this.name = 'ApiError'
}
}
/** 从 Nitro 推断的响应体上剥离一层 `ApiResponse`,得到 `data` 字段类型 */ /** 从 Nitro 推断的响应体上剥离一层 `ApiResponse`,得到 `data` 字段类型 */
export type UnwrapApiResponse<T> = T extends ApiResponse<infer D> ? D : T export type UnwrapApiResponse<T> = T extends ApiResponse<infer D> ? D : T
export function unwrapApiBody<T>(payload: ApiResponse<T>): T { export function unwrapApiBody<T>(payload: ApiResponse<T>): T {
if (payload.code !== 0) { if (payload.code !== 0) {
throw new Error(payload.message) throw new ApiError(payload.message, payload.data)
} }
return payload.data return payload.data
} }

Loading…
Cancel
Save