feat(platform-web): surface backend api errors
This commit is contained in:
@@ -28,15 +28,40 @@ export type RawFrameQuery = {
|
||||
offset?: number;
|
||||
};
|
||||
|
||||
type ApiErrorEnvelope = {
|
||||
error?: {
|
||||
code?: string;
|
||||
message?: string;
|
||||
detail?: string;
|
||||
};
|
||||
};
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const response = await fetch(path, init);
|
||||
if (!response.ok) {
|
||||
throw new Error(`request failed ${response.status}`);
|
||||
throw new Error(await responseErrorMessage(response));
|
||||
}
|
||||
const envelope = (await response.json()) as ApiEnvelope<T>;
|
||||
return envelope.data;
|
||||
}
|
||||
|
||||
async function responseErrorMessage(response: Response) {
|
||||
try {
|
||||
const envelope = (await response.json()) as ApiErrorEnvelope;
|
||||
const message = envelope.error?.message?.trim();
|
||||
const detail = envelope.error?.detail?.trim();
|
||||
if (message && detail) {
|
||||
return `${message}: ${detail}`;
|
||||
}
|
||||
if (message) {
|
||||
return message;
|
||||
}
|
||||
} catch {
|
||||
// Fall back to status when the server does not return the platform envelope.
|
||||
}
|
||||
return `request failed ${response.status}`;
|
||||
}
|
||||
|
||||
export const api = {
|
||||
dashboardSummary: () => request<DashboardSummary>('/api/dashboard/summary'),
|
||||
vehicles: (params = new URLSearchParams()) => request<Page<VehicleRow>>(`/api/vehicles?${params.toString()}`),
|
||||
|
||||
Reference in New Issue
Block a user