forked from Lilly-Protocol/lily-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.ts
More file actions
48 lines (41 loc) · 1.28 KB
/
Copy patherrors.ts
File metadata and controls
48 lines (41 loc) · 1.28 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
export interface LilyApiErrorDetails {
field?: string;
reason?: string;
}
export class LilyApiError extends Error {
public readonly status: number;
public readonly code: string;
public readonly details?: LilyApiErrorDetails[];
constructor(
message: string,
status: number,
code: string,
details?: LilyApiErrorDetails[],
) {
super(message);
this.name = "LilyApiError";
this.status = status;
this.code = code;
this.details = details;
}
}
export function isLilyApiError(error: unknown): error is LilyApiError {
return error instanceof LilyApiError;
}
export async function handleApiResponse(response: Response): Promise<void> {
if (response.ok) return;
let code = "UNKNOWN_ERROR";
let message = response.statusText || "An unexpected error occurred";
let details: LilyApiErrorDetails[] | undefined;
try {
const body = await response.json();
if (typeof body === "object" && body !== null) {
if (typeof body.code === "string") code = body.code;
if (typeof body.message === "string") message = body.message;
if (Array.isArray(body.details)) details = body.details;
}
} catch {
// Non-JSON error response; use defaults from status text
}
throw new LilyApiError(message, response.status, code, details);
}