Repository navigation
Expand file tree
/
Copy pathhttpClient.ts
More file actions
68 lines (58 loc) · 1.9 KB
/
Copy pathhttpClient.ts
File metadata and controls
68 lines (58 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
export type FetchLike = typeof fetch;
export interface ThrottleNotice {
kind: "backoff" | "burst" | "token-bucket";
seconds: number;
remaining?: number;
}
export class StackApiError extends Error {
constructor(
message: string,
public readonly status: number,
public readonly url: string,
public readonly responseText: string,
) {
super(message);
}
}
export class InvalidApiResponseError extends Error {
constructor(apiName: string) {
super(`${apiName} returned invalid JSON.`);
this.name = "InvalidApiResponseError";
}
}
export class ApiTransportError extends Error {
constructor(apiName: string) {
super(`${apiName} transport failed.`);
this.name = "ApiTransportError";
}
}
export async function readJsonResponse<T>(response: Response, apiName: string): Promise<T> {
if (!response.ok) {
const text = await response.text();
throw new StackApiError(
formatStackApiErrorMessage(apiName, response.status, text),
response.status,
response.url,
text,
);
}
try {
return (await response.json()) as T;
} catch {
throw new InvalidApiResponseError(apiName);
}
}
function formatStackApiErrorMessage(apiName: string, status: number, responseText: string): string {
const baseMessage = `${apiName} request failed with ${status}`;
try {
const body = JSON.parse(responseText) as { error_name?: unknown; error_message?: unknown };
const errorName = typeof body.error_name === "string" ? body.error_name.trim() : "";
const errorMessage = typeof body.error_message === "string" ? body.error_message.trim() : "";
if (errorName && errorMessage) return `${baseMessage}: ${errorName} - ${errorMessage}`;
if (errorMessage) return `${baseMessage}: ${errorMessage}`;
if (errorName) return `${baseMessage}: ${errorName}`;
} catch {
// Non-JSON API errors keep the concise status-only message.
}
return baseMessage;
}