/
fetch_error.ts
37 lines (36 loc) · 1.09 KB
/
fetch_error.ts
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
export default class FetchError extends Error {
constructor(
public status: number,
public details: Record<string, unknown>,
message: string,
opts?: ErrorOptions,
) {
super(message, opts);
}
static async fromResponse(res: Response): Promise<FetchError> {
let status = res.status;
let message = res.statusText;
let details: Record<string, unknown> = {};
if (status >= 300 && status < 400) {
const location = res.headers.get("Location");
if (location) {
details.location = location;
}
}
if (res.headers.get("content-type")?.startsWith("application/json")) {
const data = await res.json();
if (typeof data.status === "number") {
status = data.status;
}
if (typeof data.message === "string") {
message = data.message;
}
if (data.details !== null && typeof data.details === "object" && !Array.isArray(data.details)) {
details = { ...details, ...data.detials };
}
} else {
message = await res.text();
}
return new FetchError(status, details, message);
}
}