23 lines
596 B
TypeScript
23 lines
596 B
TypeScript
export class ApiError extends Error {
|
|
status: number;
|
|
body: string;
|
|
|
|
constructor(message: string, status: number, body: string) {
|
|
super(message);
|
|
this.name = "ApiError";
|
|
this.status = status;
|
|
this.body = body;
|
|
}
|
|
}
|
|
|
|
export async function requestJson<T>(input: RequestInfo | URL, init?: RequestInit): Promise<T> {
|
|
const res = await fetch(input, init);
|
|
|
|
if (!res.ok) {
|
|
const text = await res.text();
|
|
throw new ApiError(`Request failed with status ${res.status}`, res.status, text);
|
|
}
|
|
|
|
return (await res.json()) as T;
|
|
}
|