-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror.js
More file actions
102 lines (81 loc) · 1.93 KB
/
error.js
File metadata and controls
102 lines (81 loc) · 1.93 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import { INTERNAL_SERVER_ERROR } from '@shgysk8zer0/consts/status.js';
export class HTTPError extends Error {
#status = INTERNAL_SERVER_ERROR;
#response;
constructor(message, { status = INTERNAL_SERVER_ERROR, cause, resp } = {}) {
super(message, { cause });
if (resp instanceof Response) {
this.#response = resp;
this.#status = resp.status;
} else if (typeof status === 'number' && Number.isSafeInteger(status) && status > -1 && status < 600) {
this.#status = status;
} else {
this.#status = INTERNAL_SERVER_ERROR;
}
}
get body() {
return this.#response?.body;
}
get bodyUsed() {
return this.#response?.bodyUsed;
}
get headers() {
return this.#response?.headers;
}
get ok() {
return this.#response?.ok;
}
get redirected() {
return this.#response?.redirected;
}
get status() {
return this.#status;
}
get type() {
return this.#response?.type;
}
get url() {
return this.#response?.url;
}
async arrayBuffer() {
return this.#response?.arrayBuffer();
}
async blob() {
return this.#response?.blob();
}
async text() {
return this.#response?.text();
}
async json() {
return this.#response?.json();
}
async formData() {
return this.#response?.formData();
}
toString() {
return JSON.stringify(this);
}
toJSON() {
return {
error: {
status: this.#status,
message: this.message,
}
};
}
toResponse({ headers } = {}) {
return Response.json(this, { status: this.status, headers });
}
static async fromResponse(resp, { cause } = {}) {
if (! (resp instanceof Response)) {
throw new TypeError('resp must be a Response object.');
} else {
const { error } = await resp.clone().json();
if (typeof error !== 'object' || ! error.hasOwnProperty('message') || ! error.hasOwnProperty('status')) {
return new this(`<${resp.url}> [${resp.status} ${resp.statusText}]`, { resp, cause });
} else {
return new this(error.message, { resp, cause });
}
}
}
}