Files
edr-platform/apps/edr-freight-web/backoffice/src/utils/result.ts

30 lines
1.0 KiB
TypeScript

export type Result<T, E = { code: string; message: string; statusCode?: number }> =
| { 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<string, unknown>;
const response = obj.response as Record<string, unknown> | undefined;
if (response) {
const statusCode = response.status as number | undefined;
const data = response.data as Record<string, unknown> | 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" };
}