-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapiError.ts
88 lines (73 loc) · 1.83 KB
/
apiError.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
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
export class ApiError<T extends object> extends Error {
public constructor(
public readonly status: number,
public readonly message: string,
public readonly code: string,
public readonly data: T
) {
super(message);
}
}
export class AppError extends Error {
constructor(message: string) {
super(message);
}
}
export class HttpError extends Error {
constructor(message: string, options: ErrorOptions) {
super(message, options);
}
}
export class APIError<T = unknown> extends HttpError {
statusCode: number = 500;
fatal = false;
statusMessage?: string;
data?: T;
cause?: unknown;
constructor(message: string, options: { cause?: unknown } = {}) {
super(message, options);
}
}
export function createError<T = unknown>(
input:
| string
| (Partial<APIError<T>> & { status?: number; statusText?: string })
): APIError<T> {
if (input instanceof APIError) {
return input;
}
if (typeof input === "string") {
return new APIError<T>(input);
}
const cause: unknown = input.cause;
const err = new APIError<T>(input.message ?? input.statusMessage ?? "", {
cause: cause || input,
});
if ("stack" in input) {
err.stack = input.stack;
}
if (input.data) {
err.data = input.data;
}
const statusCode =
input.statusCode ??
input.status ??
(cause as APIError)?.statusCode ??
(cause as { status?: number })?.status;
if (typeof statusCode === "number") {
err.statusCode = statusCode;
}
const statusMessage =
input.statusMessage ??
input.statusText ??
(cause as APIError)?.statusMessage ??
(cause as { statusText?: string })?.statusText;
if (statusMessage) {
err.statusMessage = statusMessage;
}
const fatal = input.fatal ?? (cause as APIError)?.fatal;
if (fatal !== undefined) {
err.fatal = fatal;
}
return err;
}