forked from Lilly-Protocol/lily-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgh-disc-75-Lilly-Protocol-lily-frontend.ts
More file actions
57 lines (46 loc) · 1.66 KB
/
Copy pathgh-disc-75-Lilly-Protocol-lily-frontend.ts
File metadata and controls
57 lines (46 loc) · 1.66 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
// types/api-error.ts
export interface ApiErrorDetails {
[key: string]: string | string[] | undefined;
}
export class ApiError extends Error {
readonly status: number;
readonly details?: ApiErrorDetails;
constructor(status: number, message: string, details?: ApiErrorDetails) {
super(message);
this.status = status;
this.details = details;
Object.setPrototypeOf(this, ApiError.prototype);
}
static fromResponse(response: Response): ApiError {
const status = response.status;
let message = response.statusText;
let details: ApiErrorDetails | undefined;
if (response.ok) {
throw new Error("Cannot create ApiError from successful response");
}
// Try to parse JSON error body
response.clone().json().then((data) => {
if (data?.message) message = data.message;
if (data?.details) details = data.details;
}).catch(() => {
// Fallback if not JSON
});
// For synchronous usage, assume defaults if parsing fails
return new ApiError(status, message, details);
}
static badRequest(message: string, details?: ApiErrorDetails): ApiError {
return new ApiError(400, message, details);
}
static unauthorized(message: string, details?: ApiErrorDetails): ApiError {
return new ApiError(401, message, details);
}
static forbidden(message: string, details?: ApiErrorDetails): ApiError {
return new ApiError(403, message, details);
}
static notFound(message: string, details?: ApiErrorDetails): ApiError {
return new ApiError(404, message, details);
}
static internal(message: string, details?: ApiErrorDetails): ApiError {
return new ApiError(500, message, details);
}
}