-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror.ts
More file actions
71 lines (58 loc) · 1.74 KB
/
error.ts
File metadata and controls
71 lines (58 loc) · 1.74 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
69
70
71
export const APIErrorCodes = {
InvalidUUID: "InvalidUUID",
InvalidMUID: "InvalidMUID",
UUIDNotFound: "UUIDNotFound",
MUIDNotFound: "MUIDNotFound",
VoterNameNotFound: "VoterNameNotFound",
UUIDAlreadyClaimed: "UUIDAlreadyClaimed",
NameTaken: "NameTaken",
AlreadyRegistered: "AlreadyRegistered",
MUIDMismatch: "MUIDMismatch",
InvalidMetaData: "InvalidMetaData",
InvalidVoteMethod: "InvalidVoteMethod",
InvalidVoteLength: "InvalidVoteLength",
VotingInactive: "VotingInactive",
SignatureInvalid: "SignatureInvalid",
SignatureExpired: "SignatureExpired",
SignatureFailure: "SignatureFailure",
InvalidState: "InvalidState",
AuthError: "AuthError",
InvalidStatusCode: "InvalidStatusCode",
};
export type APIErrorCode = (typeof APIErrorCodes)[keyof typeof APIErrorCodes];
export type APIError = {
error: {
code: APIErrorCode;
message: string;
httpStatus: number;
timestamp: string;
};
endpoint: {
method: string;
path: string;
};
};
export class APIRequestError extends Error {
readonly apiError: APIError;
constructor(apiError: APIError) {
super(apiError.error.message);
this.name = "APIRequestError";
this.apiError = apiError;
}
}
/**
* Parses the error body from a non-ok Response and throws an `APIRequestError`.
* Falls back to a generic `Error("HTTP <status>")` if the body is not a valid
* `APIError`.
*
* Must be called before consuming the response body (i.e. before `res.json()`).
*/
export async function handleErrorResponse(res: Response): Promise<never> {
try {
const apiError: APIError = await res.json();
throw new APIRequestError(apiError);
} catch (e) {
if (e instanceof APIRequestError) throw e;
throw new Error(`HTTP ${res.status}`);
}
}