21 lines
726 B
TypeScript
21 lines
726 B
TypeScript
export type ApiError = { code: number; msg: string }
|
|
|
|
export type ApiDecision = { ok: true } | { ok: false; error: ApiError }
|
|
|
|
export function isApiError(value: unknown): value is ApiError {
|
|
if (typeof value !== "object" || value === null) return false
|
|
|
|
const v = value as { code?: unknown; msg?: unknown }
|
|
return typeof v.code === "number" && typeof v.msg === "string"
|
|
}
|
|
|
|
export function toApiError(err: unknown): ApiError {
|
|
if (isApiError(err)) return err
|
|
if (err instanceof Error) return { code: 500, msg: err.message }
|
|
if (typeof err === "string") return { code: 500, msg: err }
|
|
|
|
return { code: 500, msg: "Unknown error" }
|
|
}
|
|
|
|
export type ApiResult<T> = { ok: true; data: T } | { ok: false; error: ApiError }
|