@web-ts-toolkit/http-errors 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -282
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -8,9 +8,12 @@ HTTP error classes for backend APIs, including 4xx client errors and 5xx server
|
|
|
8
8
|
npm install @web-ts-toolkit/http-errors
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
##
|
|
11
|
+
## Documentation
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
- Full package documentation lives in `website/docs/packages/http-errors.md`.
|
|
14
|
+
- Use the Docusaurus site in `website` for the complete hierarchy, payload helpers, and Express examples.
|
|
15
|
+
|
|
16
|
+
## Minimal Example
|
|
14
17
|
|
|
15
18
|
```ts
|
|
16
19
|
import { HttpError, UnauthorizedError, ServiceUnavailableError } from '@web-ts-toolkit/http-errors';
|
|
@@ -23,283 +26,3 @@ throw new HttpError(503, 'please try again later');
|
|
|
23
26
|
|
|
24
27
|
throw new ServiceUnavailableError();
|
|
25
28
|
```
|
|
26
|
-
|
|
27
|
-
### Use a specific 4xx error
|
|
28
|
-
|
|
29
|
-
```ts
|
|
30
|
-
import { BadRequestError } from '@web-ts-toolkit/http-errors';
|
|
31
|
-
|
|
32
|
-
function parseLimit(value: string | undefined): number {
|
|
33
|
-
const limit = Number(value);
|
|
34
|
-
|
|
35
|
-
if (!Number.isInteger(limit) || limit <= 0) {
|
|
36
|
-
throw new BadRequestError('limit must be a positive integer');
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
return limit;
|
|
40
|
-
}
|
|
41
|
-
```
|
|
42
|
-
|
|
43
|
-
### Use the category base classes
|
|
44
|
-
|
|
45
|
-
```ts
|
|
46
|
-
import { ClientError, ServerError } from '@web-ts-toolkit/http-errors';
|
|
47
|
-
|
|
48
|
-
throw new ClientError(403, 'forbidden project access');
|
|
49
|
-
throw new ServerError(503, 'search index is rebuilding');
|
|
50
|
-
```
|
|
51
|
-
|
|
52
|
-
### Attach a cause
|
|
53
|
-
|
|
54
|
-
```ts
|
|
55
|
-
import { ServiceUnavailableError } from '@web-ts-toolkit/http-errors';
|
|
56
|
-
|
|
57
|
-
try {
|
|
58
|
-
await fetch('https://api.example.com/health');
|
|
59
|
-
} catch (cause) {
|
|
60
|
-
throw new ServiceUnavailableError('upstream API is unavailable', { cause });
|
|
61
|
-
}
|
|
62
|
-
```
|
|
63
|
-
|
|
64
|
-
### Add machine-readable error metadata
|
|
65
|
-
|
|
66
|
-
```ts
|
|
67
|
-
import { BadRequestError } from '@web-ts-toolkit/http-errors';
|
|
68
|
-
|
|
69
|
-
throw new BadRequestError('invalid email', {
|
|
70
|
-
reason: 'INVALID_EMAIL',
|
|
71
|
-
domain: 'api.example.com',
|
|
72
|
-
type: 'https://api.example.com/problems/invalid-email',
|
|
73
|
-
title: 'Invalid email address',
|
|
74
|
-
instance: '/problems/invalid-email/123',
|
|
75
|
-
metadata: {
|
|
76
|
-
field: 'email',
|
|
77
|
-
},
|
|
78
|
-
details: [
|
|
79
|
-
{
|
|
80
|
-
type: 'help',
|
|
81
|
-
links: [
|
|
82
|
-
{
|
|
83
|
-
description: 'Validation guide',
|
|
84
|
-
url: 'https://api.example.com/docs/errors/invalid-email',
|
|
85
|
-
},
|
|
86
|
-
],
|
|
87
|
-
},
|
|
88
|
-
],
|
|
89
|
-
errors: [
|
|
90
|
-
{
|
|
91
|
-
field: 'email',
|
|
92
|
-
description: 'Email must be a valid address.',
|
|
93
|
-
},
|
|
94
|
-
],
|
|
95
|
-
});
|
|
96
|
-
```
|
|
97
|
-
|
|
98
|
-
The base `HttpError` now carries optional structured fields that are useful when building AIP-193 and RFC 9457 error payloads:
|
|
99
|
-
|
|
100
|
-
- `statusCode`: HTTP status code
|
|
101
|
-
- `status`: canonical status string for common HTTP codes, otherwise `UNKNOWN`
|
|
102
|
-
- `reason`: application-specific machine-readable identifier
|
|
103
|
-
- `domain`: logical error domain such as `api.example.com`
|
|
104
|
-
- `type`: RFC 9457 problem type URI
|
|
105
|
-
- `title`: RFC 9457 problem title
|
|
106
|
-
- `instance`: RFC 9457 problem instance URI
|
|
107
|
-
- `metadata`: stringified key-value metadata
|
|
108
|
-
- `details`: structured detail entries
|
|
109
|
-
- `errors`: validation or field-level error payloads
|
|
110
|
-
|
|
111
|
-
### Convert an error to an AIP-193-style payload
|
|
112
|
-
|
|
113
|
-
```ts
|
|
114
|
-
import { BadRequestError, toAip193ErrorPayload } from '@web-ts-toolkit/http-errors';
|
|
115
|
-
|
|
116
|
-
const error = new BadRequestError('invalid email', {
|
|
117
|
-
reason: 'INVALID_EMAIL',
|
|
118
|
-
domain: 'api.example.com',
|
|
119
|
-
metadata: {
|
|
120
|
-
field: 'email',
|
|
121
|
-
},
|
|
122
|
-
});
|
|
123
|
-
|
|
124
|
-
const payload = toAip193ErrorPayload(error);
|
|
125
|
-
```
|
|
126
|
-
|
|
127
|
-
### Convert an error to an RFC 9457 payload
|
|
128
|
-
|
|
129
|
-
```ts
|
|
130
|
-
import { BadRequestError, toRfc9457ErrorPayload } from '@web-ts-toolkit/http-errors';
|
|
131
|
-
|
|
132
|
-
const error = new BadRequestError('Email must be a valid address.', {
|
|
133
|
-
type: 'https://api.example.com/problems/invalid-email',
|
|
134
|
-
title: 'Invalid email address',
|
|
135
|
-
instance: '/problems/invalid-email/123',
|
|
136
|
-
errors: [
|
|
137
|
-
{
|
|
138
|
-
detail: 'must be a valid email address',
|
|
139
|
-
pointer: '#/email',
|
|
140
|
-
parameter: 'email',
|
|
141
|
-
},
|
|
142
|
-
{
|
|
143
|
-
detail: 'x-request-id header is required',
|
|
144
|
-
header: 'x-request-id',
|
|
145
|
-
},
|
|
146
|
-
],
|
|
147
|
-
});
|
|
148
|
-
|
|
149
|
-
const payload = toRfc9457ErrorPayload(error);
|
|
150
|
-
```
|
|
151
|
-
|
|
152
|
-
### Use the typed RFC 9457 validation helper
|
|
153
|
-
|
|
154
|
-
```ts
|
|
155
|
-
import { BadRequestError, toRfc9457ValidationErrorPayload } from '@web-ts-toolkit/http-errors';
|
|
156
|
-
|
|
157
|
-
const error = new BadRequestError('Email must be a valid address.', {
|
|
158
|
-
type: 'https://api.example.com/problems/invalid-email',
|
|
159
|
-
title: 'Invalid email address',
|
|
160
|
-
errors: [
|
|
161
|
-
{
|
|
162
|
-
detail: 'must be a valid email address',
|
|
163
|
-
pointer: '#/email',
|
|
164
|
-
},
|
|
165
|
-
],
|
|
166
|
-
});
|
|
167
|
-
|
|
168
|
-
const payload = toRfc9457ValidationErrorPayload(error);
|
|
169
|
-
```
|
|
170
|
-
|
|
171
|
-
### Express route example
|
|
172
|
-
|
|
173
|
-
```ts
|
|
174
|
-
import express from 'express';
|
|
175
|
-
import { BadRequestError, ForbiddenError, NotFoundError } from '@web-ts-toolkit/http-errors';
|
|
176
|
-
|
|
177
|
-
type User = {
|
|
178
|
-
id: string;
|
|
179
|
-
role: 'admin' | 'member';
|
|
180
|
-
};
|
|
181
|
-
|
|
182
|
-
type Project = {
|
|
183
|
-
id: string;
|
|
184
|
-
ownerId: string;
|
|
185
|
-
name: string;
|
|
186
|
-
};
|
|
187
|
-
|
|
188
|
-
const app = express();
|
|
189
|
-
|
|
190
|
-
const projects = new Map<string, Project>([['project-1', { id: 'project-1', ownerId: 'user-1', name: 'Toolkit' }]]);
|
|
191
|
-
|
|
192
|
-
app.use(express.json());
|
|
193
|
-
|
|
194
|
-
app.put('/projects/:id', (req, res) => {
|
|
195
|
-
const user = req.user as User | undefined;
|
|
196
|
-
const project = projects.get(req.params.id);
|
|
197
|
-
|
|
198
|
-
if (!user) {
|
|
199
|
-
throw new ForbiddenError('authentication required');
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
if (!project) {
|
|
203
|
-
throw new NotFoundError('project was not found');
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
if (project.ownerId !== user.id && user.role !== 'admin') {
|
|
207
|
-
throw new ForbiddenError('you cannot update this project');
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
if (typeof req.body.name !== 'string' || req.body.name.trim() === '') {
|
|
211
|
-
throw new BadRequestError('name is required');
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
project.name = req.body.name.trim();
|
|
215
|
-
res.json(project);
|
|
216
|
-
});
|
|
217
|
-
```
|
|
218
|
-
|
|
219
|
-
### Express error middleware example
|
|
220
|
-
|
|
221
|
-
```ts
|
|
222
|
-
import type { NextFunction, Request, Response } from 'express';
|
|
223
|
-
import express from 'express';
|
|
224
|
-
import { HttpError, InternalServerError } from '@web-ts-toolkit/http-errors';
|
|
225
|
-
|
|
226
|
-
const app = express();
|
|
227
|
-
|
|
228
|
-
app.use((err: unknown, _req: Request, res: Response, _next: NextFunction) => {
|
|
229
|
-
if (err instanceof HttpError) {
|
|
230
|
-
return res.status(err.statusCode).json({
|
|
231
|
-
error: {
|
|
232
|
-
name: err.name,
|
|
233
|
-
message: err.message,
|
|
234
|
-
statusCode: err.statusCode,
|
|
235
|
-
},
|
|
236
|
-
});
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
const fallback = new InternalServerError('unexpected server error');
|
|
240
|
-
|
|
241
|
-
return res.status(fallback.statusCode).json({
|
|
242
|
-
error: {
|
|
243
|
-
name: fallback.name,
|
|
244
|
-
message: fallback.message,
|
|
245
|
-
statusCode: fallback.statusCode,
|
|
246
|
-
},
|
|
247
|
-
});
|
|
248
|
-
});
|
|
249
|
-
```
|
|
250
|
-
|
|
251
|
-
## Error Hierarchy
|
|
252
|
-
|
|
253
|
-
`HttpError` is the neutral base class for HTTP responses.
|
|
254
|
-
|
|
255
|
-
`ClientError` is the base class for 4xx responses.
|
|
256
|
-
|
|
257
|
-
`ServerError` is the base class for 5xx responses.
|
|
258
|
-
|
|
259
|
-
## Client Errors
|
|
260
|
-
|
|
261
|
-
| Code | Description | Class Name | Default Message |
|
|
262
|
-
| ---- | ------------------------------- | --------------------------------- | ---------------------------------------------------------------------------------------------------------- |
|
|
263
|
-
| 400 | Bad Request | BadRequestError | The server cannot process the request due to a client error |
|
|
264
|
-
| 401 | Unauthorized | UnauthorizedError | The user is not authorized |
|
|
265
|
-
| 403 | Forbidden | ForbiddenError | The server refused to authorize the request |
|
|
266
|
-
| 404 | Not Found | NotFoundError | The server did not find a current representation for the target resource |
|
|
267
|
-
| 405 | Method Not Allowed | MethodNotAllowedError | The method received is not allowed |
|
|
268
|
-
| 406 | Not Acceptable | NotAcceptableError | The request is not acceptable to the user agent |
|
|
269
|
-
| 407 | Proxy Authentication Required | ProxyAuthRequiredError | The client needs to authenticate itself in order to use a proxy |
|
|
270
|
-
| 408 | Request Timeout | RequestTimeoutError | The request was not completed in the expected time |
|
|
271
|
-
| 409 | Conflict | ConflictError | The request was not completed due to a conflict with the target resource |
|
|
272
|
-
| 410 | Gone | GoneError | The target resource is no longer available at the origin server |
|
|
273
|
-
| 411 | Length Required | LengthRequiredError | The server refuses to accept the request without a defined Content-Length |
|
|
274
|
-
| 412 | Precondition Failed | PreconditionFailedError | One or more conditions given in the request header fields evaluated to false |
|
|
275
|
-
| 413 | Payload Too Large | PayloadTooLargeError | The request payload is too large |
|
|
276
|
-
| 414 | URI Too Long | UriTooLongError | The request target is too long |
|
|
277
|
-
| 415 | Unsupported Media Type | UnsupportedMediaTypeError | The payload is in a format not supported |
|
|
278
|
-
| 416 | Requested Range Not Satisfiable | RequestedRangeNotSatisfiableError | None of the ranges in the request's Range header field overlap the current extent of the selected resource |
|
|
279
|
-
| 417 | Expectation Failed | ExpectationFailedError | The expectation given in the request's Expect header field could not be met |
|
|
280
|
-
| 418 | I'm a teapot | TeapotError | I'm a teapot |
|
|
281
|
-
| 421 | Misdirected Request | MisdirectedRequestError | The request was directed at a server that is not able to produce a response |
|
|
282
|
-
| 422 | Unprocessable Entity | UnprocessableEntityError | The server is unable to process the request |
|
|
283
|
-
| 423 | Locked | LockedError | The source or destination resource of a method is locked |
|
|
284
|
-
| 424 | Failed Dependency | FailedDependencyError | The requested action depended on another action |
|
|
285
|
-
| 426 | Upgrade Required | UpgradeRequiredError | This service requires use of a different protocol |
|
|
286
|
-
| 428 | Precondition Required | PreconditionRequiredError | This request is required to be conditional |
|
|
287
|
-
| 429 | Too Many Requests | TooManyRequestsError | The user has sent too many requests in a given amount of time |
|
|
288
|
-
| 431 | Request Header Fields Too Large | RequestHeaderFieldsTooLargeError | Request header fields too large |
|
|
289
|
-
| 451 | Unavailable For Legal Reasons | UnavailableForLegalReasonsError | Denied access due to a consequence of a legal demand |
|
|
290
|
-
|
|
291
|
-
## Server Errors
|
|
292
|
-
|
|
293
|
-
| Code | Description | Class Name | Default Message |
|
|
294
|
-
| ---- | ------------------------------- | ---------------------------------- | ------------------------------------------------------------------------------- |
|
|
295
|
-
| 500 | Internal Server Error | InternalServerError | The server encountered an unexpected condition |
|
|
296
|
-
| 501 | Not Implemented | NotImplementedError | The server does not support the functionality required to fulfill the request |
|
|
297
|
-
| 502 | Bad Gateway | BadGatewayError | The server received an invalid response from an upstream server |
|
|
298
|
-
| 503 | Service Unavailable | ServiceUnavailableError | The server is temporarily unable to handle the request |
|
|
299
|
-
| 504 | Gateway Timeout | GatewayTimeoutError | The server did not receive a timely response from an upstream server |
|
|
300
|
-
| 505 | HTTP Version Not Supported | HttpVersionNotSupportedError | The server does not support the HTTP protocol version used in the request |
|
|
301
|
-
| 506 | Variant Also Negotiates | VariantAlsoNegotiatesError | The server has an internal configuration error |
|
|
302
|
-
| 507 | Insufficient Storage | InsufficientStorageError | The server is unable to store the representation needed to complete the request |
|
|
303
|
-
| 508 | Loop Detected | LoopDetectedError | The server detected an infinite loop while processing the request |
|
|
304
|
-
| 510 | Not Extended | NotExtendedError | Further extensions to the request are required for the server to fulfill it |
|
|
305
|
-
| 511 | Network Authentication Required | NetworkAuthenticationRequiredError | The client needs to authenticate to gain network access |
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@web-ts-toolkit/http-errors",
|
|
3
3
|
"description": "HTTP error classes for backend APIs",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.3.0",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"http-errors",
|
|
7
7
|
"api-errors"
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
}
|
|
19
19
|
},
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@web-ts-toolkit/utils": "0.
|
|
21
|
+
"@web-ts-toolkit/utils": "0.3.0"
|
|
22
22
|
},
|
|
23
23
|
"author": "Junmin Ahn",
|
|
24
24
|
"bugs": {
|