generated from shgysk8zer0/npm-template
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHTTPError.js
More file actions
62 lines (52 loc) · 1.13 KB
/
HTTPError.js
File metadata and controls
62 lines (52 loc) · 1.13 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
export class HTTPError extends Error {
#status = 0;
#headers;
constructor(message, { status = 500, headers, cause } = {}) {
if (! Number.isSafeInteger(status) && status > 0 && status < 600) {
throw new TypeError(`Invalid status: ${status}.`);
} else {
super(message, { cause });
this.#status = status;
if (headers instanceof Headers) {
this.#headers = headers;
} else {
this.#headers = new Headers(headers);
}
}
}
[Symbol.toStringTag]() {
return 'HTTPError';
}
toJSON() {
return {
name: this.name,
message: this.message,
status: this.#status,
};
}
get name() {
return 'HTTPError';
}
get headers() {
return this.#headers;
}
get status() {
return this.#status;
}
get response() {
return Response.json({
error: this,
}, {
status: this.#status,
headers: this.#headers,
});
}
static async from(resp) {
if (! (resp instanceof Response)) {
throw new TypeError('Cannot create an HTTPError without a Response.');
} else {
const { error: { status, headers, message } = {}} = await resp.json();
return new HTTPError(message, status, { headers });
}
}
}