diff --git a/apps/edr-freight-web/portal/src/utils/result.ts b/apps/edr-freight-web/portal/src/utils/result.ts new file mode 100644 index 000000000..3e9627445 --- /dev/null +++ b/apps/edr-freight-web/portal/src/utils/result.ts @@ -0,0 +1,29 @@ +export type Result = + | { success: true; data: T } + | { success: false; error: E }; + +export type ApiError = { + code: string; + message: string; + statusCode?: number; +}; + +export function extractApiError(err: unknown): ApiError { + if (err && typeof err === "object") { + const obj = err as Record; + const response = obj.response as Record | undefined; + if (response) { + const statusCode = response.status as number | undefined; + const data = response.data as Record | undefined; + return { + code: (data?.error as string) || (data?.message as string) || "api_error", + message: (data?.message as string) || (data?.error as string) || "An unexpected error occurred", + statusCode, + }; + } + if (obj.message && typeof obj.message === "string") { + return { code: "client_error", message: obj.message }; + } + } + return { code: "unknown_error", message: "An unexpected error occurred" }; +}