mirror of
https://github.com/Sea-Haven-Industries/shoc-frontend-new.git
synced 2026-09-30 11:33:12 +00:00
46 lines
1.2 KiB
TypeScript
46 lines
1.2 KiB
TypeScript
|
|
export class ApiError extends Error {
|
||
|
|
readonly status: number;
|
||
|
|
|
||
|
|
constructor(message: string, status: number) {
|
||
|
|
super(message);
|
||
|
|
this.name = "ApiError";
|
||
|
|
this.status = status;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
export function mapHttpStatusToMessage(status: number, data?: unknown): string {
|
||
|
|
if (status === 401) {
|
||
|
|
return "You are not authorized to access this page.";
|
||
|
|
}
|
||
|
|
if (status === 403) {
|
||
|
|
return "You do not have permission to perform this action.";
|
||
|
|
}
|
||
|
|
if (status === 404) {
|
||
|
|
return "The requested resource was not found.";
|
||
|
|
}
|
||
|
|
if (status === 500) {
|
||
|
|
return "A server error occurred. Please try again later.";
|
||
|
|
}
|
||
|
|
|
||
|
|
if (data && typeof data === "object") {
|
||
|
|
const record = data as Record<string, unknown>;
|
||
|
|
const message = record.message ?? record.Message ?? record.error;
|
||
|
|
if (typeof message === "string" && message.length > 0) {
|
||
|
|
return message;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return "An error occurred";
|
||
|
|
}
|
||
|
|
|
||
|
|
export async function createApiErrorFromResponse(response: Response): Promise<ApiError> {
|
||
|
|
let data: unknown;
|
||
|
|
try {
|
||
|
|
data = await response.json();
|
||
|
|
} catch {
|
||
|
|
data = undefined;
|
||
|
|
}
|
||
|
|
|
||
|
|
return new ApiError(mapHttpStatusToMessage(response.status, data), response.status);
|
||
|
|
}
|