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; 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 { let data: unknown; try { data = await response.json(); } catch { data = undefined; } return new ApiError(mapHttpStatusToMessage(response.status, data), response.status); }