mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-09-07 23:35:42 +00:00
feat(utils): Introduce Result type and API error extraction utility
This commit is contained in:
29
apps/edr-freight-web/portal/src/utils/result.ts
Normal file
29
apps/edr-freight-web/portal/src/utils/result.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
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" };
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user