@appweaver/skill 0.0.0-stage → 3.1.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.
@@ -0,0 +1,486 @@
1
+ # Errors
2
+
3
+ Appweaver separates the errors of the framework from their HTTP representation. The services, utilities, queues,
4
+ schedulers and every other part of the code throw an `AppweaverError`, which carries a stable `code` and the `details`
5
+ of the error but no HTTP status, so the same service behaves the same whether a route, a queue worker, a scheduled job
6
+ or a script calls it. Only the API layer maps the code to an HTTP status and responds with the
7
+ [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) problem details of the error.
8
+
9
+ ## Error response
10
+
11
+ Every error response has the `application/problem+json` content type and the same shape, so a client tells the error
12
+ cases apart by their `code` instead of parsing messages:
13
+
14
+ ```json
15
+ {
16
+ "type": "urn:appweaver:error:database-unique-violation",
17
+ "title": "Unique constraint violation",
18
+ "status": 409,
19
+ "code": "DATABASE_UNIQUE_VIOLATION",
20
+ "detail": "User with the same email already exists",
21
+ "instance": "/api/users",
22
+ "requestId": "req-3f",
23
+ "errors": [
24
+ {
25
+ "field": "email",
26
+ "rule": "unique",
27
+ "message": "must be unique"
28
+ }
29
+ ],
30
+ "details": {
31
+ "model": "User",
32
+ "fields": ["email"]
33
+ }
34
+ }
35
+ ```
36
+
37
+ | Member | Description |
38
+ |-------------|--------------------------------------------------------------------------------------------------------------|
39
+ | `type` | URI of the problem type, the `APP_TYPE_BASE` config (`urn:appweaver`), `error` and the kebab-case code |
40
+ | `title` | Short summary of the error code, the same for every occurrence |
41
+ | `status` | HTTP status code of the response |
42
+ | `code` | The `ErrorCode` value (from `@appweaver/common`) or the code of an application error |
43
+ | `detail` | Explanation of this occurrence of the error |
44
+ | `instance` | Path of the request, without the query string |
45
+ | `requestId` | Id of the request, matching the `reqId` of the server logs |
46
+ | `traceId` | Id of the OpenTelemetry trace of the request, when it is traced (see [telemetry](./telemetry.md)) |
47
+ | `errors` | Invalid fields of the request (`field`, `rule`, `message`, optional JSON `pointer`), when the error has them |
48
+ | `details` | Details specific to the error code, i.e. the `fields` of a constraint violation or the `maxCount` of files |
49
+
50
+ - A request failing the schema validation responds with `VALIDATION_FAILED` and an entry of `errors` per invalid field,
51
+ i.e.
52
+ `{ "field": "author.email", "rule": "format", "message": "must match format \"email\"", "pointer": "#/body/author/email" }`.
53
+ A property the schema does not declare is an error too, never dropped:
54
+ `{ "field": "filter.titel", "rule": "additionalProperties", "message": "is not allowed", "pointer": "#/querystring/filter/titel" }`.
55
+ - A failed validation reports every invalid field of the failing request part (params, body, then querystring), up to
56
+ `SERVER_ERROR_RESPONSE_MAX_COUNT` errors (default `20`). With a count of `1` it stops at the first one. A value
57
+ failing a union (a relation item that is an id, an inline update or an inline create, a filter value that is a plain
58
+ value or a condition object) reports the errors of the shape it matches best, not one per shape tried, and type
59
+ mismatches merge into one, i.e. "must be object or integer".
60
+ - A database constraint violation responds with a `DATABASE_*` code naming the violated fields, both in `details.fields`
61
+ and in `errors`: unique (`409`), foreign key (`409`), not null, value too long, value out of range and invalid value
62
+ (`400`).
63
+ - The `detail` of a database error is the framework message only, i.e. "User with the same email already exists".
64
+ Set `SERVER_ERROR_DATABASE_MESSAGE_ENABLED` to append the message of the database in parentheses, in every
65
+ environment, i.e. "(Unique constraint failed on the fields: (email))", without the query and code frame of the
66
+ Prisma error. Outside production the `detail` of any other error is followed by the message of its cause.
67
+ - In production a 5xx response leaves out the `details`, and the `detail` of an unknown error is its title only.
68
+ - A response that already set a content type other than JSON, i.e. a file stream, receives the `detail` as plain text.
69
+ - A request matching no route responds with `ROUTE_NOT_FOUND`, and a rate limited one with `RATE_LIMITED` and the
70
+ seconds to wait in `details.retryAfter`.
71
+ - The errors of Fastify and its plugins are converted into the class of their code, i.e. a too large upload into a
72
+ `FileError` with `FILE_TOO_LARGE`.
73
+ - The 5xx errors are logged with their whole `cause` chain, the 4xx ones are not logged.
74
+
75
+ ## Error classes
76
+
77
+ Every class extends the abstract `AppweaverError` of `@appweaver/common` and accepts only the codes of its module, by
78
+ their prefix:
79
+
80
+ | Class | Package | Codes | Raised by |
81
+ |----------------------|---------------------|------------------|------------------------------------------------------------------------------------------|
82
+ | `RequestError` | `@appweaver/common` | request codes | The API layer, or the application for a rejected request |
83
+ | `ConfigurationError` | `@appweaver/common` | `CONFIGURATION_` | Invalid configuration and model definitions |
84
+ | `ApplicationError` | `@appweaver/common` | any | The application, with its own codes (see below) |
85
+ | `ContextError` | `@appweaver/common` | `CONTEXT_` | The dependency injection container |
86
+ | `ModuleError` | `@appweaver/common` | `MODULE_` | The module discovery and the provider selection at startup |
87
+ | `DatabaseError` | `@appweaver/common` | `DATABASE_` | The database operations, translated from the Prisma errors |
88
+ | `ResourceError` | `@appweaver/common` | `RESOURCE_` | The resource services and their query, sort and relation inputs |
89
+ | `AuthError` | `@appweaver/common` | `AUTH_` | The authentication and authorization |
90
+ | `AccountError` | `@appweaver/common` | `ACCOUNT_` | The account and 2FA services (email and phone verification, password reset, 2FA methods) |
91
+ | `OAuth2Error` | `@appweaver/common` | `OAUTH2_` | The OAuth2 sign-in |
92
+ | `RecaptchaError` | `@appweaver/common` | `RECAPTCHA_` | The reCAPTCHA verification |
93
+ | `TurnstileError` | `@appweaver/common` | `TURNSTILE_` | The Cloudflare Turnstile verification |
94
+ | `FileError` | `@appweaver/common` | `FILE_` | The file service and storage |
95
+ | `ExportError` | `@appweaver/common` | `EXPORT_` | The data export |
96
+ | `QueueError` | `@appweaver/common` | `QUEUE_` | The queues |
97
+ | `MailerError` | `@appweaver/common` | `MAILER_` | A mailer, i.e. an email the SMTP server rejects, or the email service wrapping its error |
98
+ | `SmsError` | `@appweaver/common` | `SMS_` | An SMS sender, i.e. a message Twilio rejects, or the SMS service wrapping its error |
99
+ | `TemplateError` | `@appweaver/common` | `TEMPLATE_` | The template engine: a missing, unreadable or failing template |
100
+ | `LocaleError` | `@appweaver/common` | `LOCALE_` | The locale service: an unreadable file or an invalid message |
101
+ | `LockError` | `@appweaver/common` | `LOCK_` | A lock that could not be acquired |
102
+ | `TimeSeriesError` | `@appweaver/common` | `TIMESERIES_` | The time series service and stores: invalid points and queries |
103
+ | `SpatialError` | `@appweaver/common` | `SPATIAL_` | The spatial fields: invalid geometries and spatial filters |
104
+ | `RealtimeError` | `@appweaver/common` | `REALTIME_` | The realtime connections: tickets, subscriptions, actions, streams and limits |
105
+ | `AiError` | `@appweaver/common` | `AI_` | The AI models: unknown models, missing capabilities, provider failures, invalid objects |
106
+ | `McpError` | `@appweaver/common` | `MCP_` | The MCP server: denied origins, invalid tool inputs, results too large, rate limits |
107
+ | `PaymentError` | `@appweaver/common` | `PAYMENT_` | The payments: declined payments, failed gateway requests, invalid states and webhooks |
108
+
109
+ ```ts
110
+ import { ErrorCode } from '@appweaver/common';
111
+ import { ResourceError } from '@appweaver/common';
112
+
113
+ throw new ResourceError(ErrorCode.ResourceNotFound, 'Order not found', {
114
+ model: 'Order',
115
+ id
116
+ });
117
+ ```
118
+
119
+ The constructor takes the code, the message, the `details` (typed per code by `ErrorDetailsMap`, optional for the codes
120
+ that require none) and the standard `ErrorOptions`, whose `cause` keeps the error it wraps. `error.is(code)` checks the
121
+ code and narrows the details, `isAppweaverError(error)` recognizes an error of any copy of the package, and
122
+ `JSON.stringify(error)` writes its `name`, `code`, `module`, `message`, `details` and the message of its `cause`.
123
+
124
+ ## Error codes
125
+
126
+ The `ErrorCode` enum of `@appweaver/common` lists every code the framework raises, mapped to its HTTP status by
127
+ `errorHttpMap` of `@appweaver/web`:
128
+
129
+ | Code | Status | Title |
130
+ |---------------------------------------------|--------|-------------------------------------------------|
131
+ | `INTERNAL_ERROR` | 500 | Internal server error |
132
+ | `VALIDATION_FAILED` | 400 | Validation failed |
133
+ | `MALFORMED_REQUEST` | 400 | Malformed request |
134
+ | `UNSUPPORTED_MEDIA_TYPE` | 415 | Unsupported media type |
135
+ | `PAYLOAD_TOO_LARGE` | 413 | Payload too large |
136
+ | `ROUTE_NOT_FOUND` | 404 | Route not found |
137
+ | `RATE_LIMITED` | 429 | Too many requests |
138
+ | `REQUEST_FAILED` | 400 | Request failed |
139
+ | `REQUEST_TIMEOUT` | 503 | Request timed out |
140
+ | `CONFIGURATION_INVALID` | 500 | Invalid configuration |
141
+ | `CONTEXT_DEFINITION_MISSING` | 500 | Missing context definition |
142
+ | `CONTEXT_DEFINITION_DUPLICATE` | 500 | Duplicate context definition |
143
+ | `CONTEXT_SERVER_UNAVAILABLE` | 500 | Server unavailable |
144
+ | `MODULE_INVALID` | 500 | Invalid module |
145
+ | `MODULE_MISSING` | 500 | Missing module |
146
+ | `MODULE_DUPLICATE` | 500 | Duplicate module |
147
+ | `MODULE_INCOMPATIBLE` | 500 | Incompatible module |
148
+ | `MODULE_PROVIDER_MISSING` | 500 | Missing provider |
149
+ | `MODULE_PROVIDER_AMBIGUOUS` | 500 | Ambiguous provider |
150
+ | `DATABASE_UNIQUE_VIOLATION` | 409 | Unique constraint violation |
151
+ | `DATABASE_FOREIGN_KEY_VIOLATION` | 409 | Relation constraint violation |
152
+ | `DATABASE_NULL_VIOLATION` | 400 | Required field missing |
153
+ | `DATABASE_VALUE_TOO_LONG` | 400 | Value too long |
154
+ | `DATABASE_VALUE_OUT_OF_RANGE` | 400 | Value out of range |
155
+ | `DATABASE_INVALID_VALUE` | 400 | Invalid value |
156
+ | `DATABASE_RECORD_NOT_FOUND` | 404 | Record not found |
157
+ | `DATABASE_WRITE_CONFLICT` | 409 | Write conflict |
158
+ | `DATABASE_INVALID_TRANSACTION` | 500 | Invalid transaction |
159
+ | `DATABASE_UNAVAILABLE` | 503 | Database unavailable |
160
+ | `DATABASE_OPERATION_FAILED` | 500 | Database operation failed |
161
+ | `RESOURCE_NOT_FOUND` | 404 | Resource not found |
162
+ | `RESOURCE_FORBIDDEN` | 403 | Resource access forbidden |
163
+ | `RESOURCE_INVALID_SORT` | 400 | Invalid sort |
164
+ | `RESOURCE_FILTER_TOO_COMPLEX` | 400 | Filter too complex |
165
+ | `RESOURCE_INVALID_AGGREGATE` | 400 | Invalid aggregation |
166
+ | `RESOURCE_INVALID_CURSOR` | 400 | Invalid pagination cursor |
167
+ | `RESOURCE_OFFSET_TOO_LARGE` | 400 | Page offset too large |
168
+ | `RESOURCE_PRECONDITION_FAILED` | 412 | Resource changed since it was read |
169
+ | `RESOURCE_INVALID_QUERY_PARAMETER` | 400 | Invalid query parameter |
170
+ | `RESOURCE_INVALID_RELATION` | 400 | Invalid relation |
171
+ | `RESOURCE_DELETE_RESTRICTED` | 409 | Delete restricted |
172
+ | `AUTH_UNAUTHORIZED` | 401 | Unauthorized |
173
+ | `AUTH_INVALID_CREDENTIALS` | 401 | Invalid credentials |
174
+ | `AUTH_INVALID_HEADER` | 401 | Invalid authorization header |
175
+ | `AUTH_INVALID_TOKEN` | 401 | Invalid token |
176
+ | `AUTH_TOKEN_EXPIRED` | 401 | Token expired |
177
+ | `AUTH_REFRESH_TOKEN_REUSED` | 401 | Refresh token used again |
178
+ | `AUTH_FORBIDDEN` | 403 | Forbidden |
179
+ | `AUTH_SCOPE_FORBIDDEN` | 403 | Token scope forbidden |
180
+ | `AUTH_USER_NOT_FOUND` | 400 | User not found or disabled |
181
+ | `AUTH_PASSWORD_DISABLED` | 403 | Password authentication disabled |
182
+ | `AUTH_PASSWORD_INVALID` | 403 | Invalid password |
183
+ | `AUTH_PASSWORD_WEAK` | 400 | Password too weak |
184
+ | `AUTH_PASSWORD_REQUIRED` | 401 | Password confirmation required |
185
+ | `AUTH_API_KEY_MISSING` | 401 | API key missing |
186
+ | `AUTH_API_KEY_INVALID` | 401 | Invalid API key |
187
+ | `AUTH_API_KEY_EXPIRED` | 403 | API key expired |
188
+ | `AUTH_API_KEY_PERMISSION_DENIED` | 403 | API key permission denied |
189
+ | `AUTH_PROXY_AUTHENTICATION_REQUIRED` | 407 | Proxy authentication required |
190
+ | `AUTH_INVALID_REDIRECT_URL` | 400 | Invalid redirect URL |
191
+ | `ACCOUNT_FEATURE_UNAVAILABLE` | 501 | Account feature unavailable |
192
+ | `ACCOUNT_EMAIL_ALREADY_VERIFIED` | 409 | Email already verified |
193
+ | `ACCOUNT_PASSWORD_NOT_SET` | 403 | Password not set |
194
+ | `ACCOUNT_EMAIL_NOT_VERIFIED` | 403 | Email not verified |
195
+ | `ACCOUNT_PHONE_NOT_VERIFIED` | 403 | Phone number not verified |
196
+ | `ACCOUNT_PHONE_ALREADY_VERIFIED` | 409 | Phone number already verified |
197
+ | `ACCOUNT_PHONE_NOT_SET` | 400 | Phone number not set |
198
+ | `ACCOUNT_TWO_FACTOR_METHOD_UNAVAILABLE` | 400 | 2FA method unavailable |
199
+ | `ACCOUNT_TWO_FACTOR_METHOD_NOT_ENABLED` | 400 | 2FA method not enabled |
200
+ | `ACCOUNT_TWO_FACTOR_METHOD_ALREADY_ENABLED` | 409 | 2FA method already enabled |
201
+ | `ACCOUNT_TWO_FACTOR_CODE_INVALID` | 400 | Invalid 2FA code |
202
+ | `ACCOUNT_TWO_FACTOR_TOO_MANY_ATTEMPTS` | 429 | Too many 2FA attempts |
203
+ | `OAUTH2_PROVIDER_ERROR` | 502 | OAuth2 provider error |
204
+ | `OAUTH2_EMAIL_UNAVAILABLE` | 403 | OAuth2 email unavailable |
205
+ | `OAUTH2_EMAIL_UNVERIFIED` | 403 | OAuth2 email unverified |
206
+ | `OAUTH2_REGISTRATION_DISABLED` | 403 | OAuth2 registration disabled |
207
+ | `OAUTH2_ACCOUNT_CONFLICT` | 409 | OAuth2 account linked to another user |
208
+ | `OAUTH2_USER_REJECTED` | 403 | OAuth2 user rejected |
209
+ | `RECAPTCHA_MISSING` | 400 | reCAPTCHA missing |
210
+ | `RECAPTCHA_INVALID` | 400 | Invalid reCAPTCHA |
211
+ | `RECAPTCHA_ACTION_MISMATCH` | 403 | reCAPTCHA action mismatch |
212
+ | `RECAPTCHA_LOW_SCORE` | 403 | reCAPTCHA low score |
213
+ | `RECAPTCHA_UNAVAILABLE` | 502 | reCAPTCHA unavailable |
214
+ | `TURNSTILE_MISSING` | 400 | Turnstile missing |
215
+ | `TURNSTILE_INVALID` | 400 | Invalid Turnstile |
216
+ | `TURNSTILE_ACTION_MISMATCH` | 403 | Turnstile action mismatch |
217
+ | `TURNSTILE_UNAVAILABLE` | 502 | Turnstile unavailable |
218
+ | `FILE_NOT_FOUND` | 404 | File not found |
219
+ | `FILE_FORBIDDEN` | 403 | File access forbidden |
220
+ | `FILE_FIELD_NOT_FOUND` | 400 | File field not found |
221
+ | `FILE_UNSUPPORTED_TYPE` | 415 | Unsupported file type |
222
+ | `FILE_TOO_LARGE` | 413 | File too large |
223
+ | `FILE_LIMIT_EXCEEDED` | 400 | File limit exceeded |
224
+ | `FILE_INVALID_PATH` | 400 | Invalid file path |
225
+ | `FILE_NONE_PROVIDED` | 400 | No files provided |
226
+ | `FILE_UPLOAD_FAILED` | 400 | File upload failed |
227
+ | `FILE_DELETE_FAILED` | 400 | File delete failed |
228
+ | `FILE_STORAGE_ERROR` | 500 | File storage error |
229
+ | `FILE_VERSION_NOT_FOUND` | 404 | File version not found |
230
+ | `FILE_VERSIONING_DISABLED` | 400 | File versioning disabled |
231
+ | `FILE_REPLACE_TARGET_INVALID` | 400 | Invalid file to replace |
232
+ | `EXPORT_FAILED` | 500 | Export failed |
233
+ | `QUEUE_CLOSED` | 503 | Queue closed |
234
+ | `QUEUE_UNAVAILABLE` | 503 | Queue unavailable |
235
+ | `QUEUE_JOB_TIMEOUT` | 504 | Queue job timed out |
236
+ | `MAILER_SEND_FAILED` | 502 | Email sending failed |
237
+ | `MAILER_SENDER_MISSING` | 500 | Email sender missing |
238
+ | `SMS_SEND_FAILED` | 502 | SMS sending failed |
239
+ | `TEMPLATE_NOT_FOUND` | 500 | Template not found |
240
+ | `TEMPLATE_RENDER_FAILED` | 500 | Template rendering failed |
241
+ | `TEMPLATE_LOAD_FAILED` | 500 | Template loading failed |
242
+ | `TEMPLATE_PREVIEW_NOT_FOUND` | 404 | Template preview not found |
243
+ | `LOCALE_LOAD_FAILED` | 500 | Locale loading failed |
244
+ | `LOCK_NOT_ACQUIRED` | 503 | Resource is locked |
245
+ | `MEMORY_UNAVAILABLE` | 503 | Memory unavailable |
246
+ | `MEMORY_VALUE_INVALID` | 500 | Memory value invalid |
247
+ | `TIMESERIES_NOT_ENABLED` | 404 | Time series not enabled |
248
+ | `TIMESERIES_INVALID_FIELD` | 400 | Invalid time series field |
249
+ | `TIMESERIES_INVALID_VALUE` | 400 | Invalid time series value |
250
+ | `TIMESERIES_INVALID_TIME` | 400 | Invalid time series point time |
251
+ | `TIMESERIES_INVALID_RANGE` | 400 | Invalid time series range |
252
+ | `TIMESERIES_INVALID_BUCKET` | 400 | Invalid time series bucket |
253
+ | `TIMESERIES_INVALID_AGGREGATE` | 400 | Invalid time series aggregate |
254
+ | `TIMESERIES_TOO_MANY_POINTS` | 413 | Too many time series points |
255
+ | `TIMESERIES_TOO_MANY_RESOURCES` | 400 | Too many time series resources |
256
+ | `TIMESERIES_FORBIDDEN` | 403 | Time series access forbidden |
257
+ | `TIMESERIES_UNSUPPORTED` | 501 | Time series operation not supported |
258
+ | `SPATIAL_INVALID_GEOMETRY` | 400 | Invalid geometry |
259
+ | `SPATIAL_INVALID_FILTER` | 400 | Invalid spatial filter |
260
+ | `SPATIAL_TOO_MANY_CANDIDATES` | 400 | Too many spatial matches |
261
+ | `REALTIME_TICKET_INVALID` | 401 | Invalid realtime ticket |
262
+ | `REALTIME_CHANNEL_UNKNOWN` | 404 | Unknown realtime channel |
263
+ | `REALTIME_SUBSCRIPTION_DENIED` | 403 | Realtime subscription denied |
264
+ | `REALTIME_SUBSCRIPTION_LIMIT` | 429 | Too many realtime subscriptions |
265
+ | `REALTIME_ACTION_UNKNOWN` | 404 | Unknown realtime action |
266
+ | `REALTIME_ACTION_DENIED` | 403 | Realtime action denied |
267
+ | `REALTIME_PAYLOAD_INVALID` | 400 | Invalid realtime payload |
268
+ | `REALTIME_MESSAGE_INVALID` | 400 | Invalid realtime message |
269
+ | `REALTIME_CONNECTION_LIMIT` | 429 | Too many realtime connections |
270
+ | `REALTIME_RATE_LIMITED` | 429 | Realtime messages rate limited |
271
+ | `REALTIME_TRANSPORT_DISABLED` | 404 | Realtime transport disabled |
272
+ | `REALTIME_STREAM_NOT_FOUND` | 404 | Realtime stream not found |
273
+ | `REALTIME_STREAM_ENDED` | 409 | Realtime stream ended |
274
+ | `REALTIME_STREAM_LOST` | 503 | Realtime stream lost |
275
+ | `REALTIME_STREAM_ACCEPT` | 406 | Realtime stream not accepted |
276
+ | `REALTIME_INPUT_LIMIT` | 413 | Realtime input too large |
277
+ | `REALTIME_SHUTTING_DOWN` | 503 | Realtime server shutting down |
278
+ | `AI_MODEL_UNKNOWN` | 500 | AI model unknown |
279
+ | `AI_REQUEST_INVALID` | 400 | Invalid AI request |
280
+ | `AI_CAPABILITY_UNSUPPORTED` | 400 | AI capability not supported by the model |
281
+ | `AI_REQUEST_FAILED` | 502 | AI request failed |
282
+ | `AI_AUTH_FAILED` | 502 | AI provider authentication failed |
283
+ | `AI_RATE_LIMITED` | 429 | AI provider rate limited |
284
+ | `AI_TIMEOUT` | 504 | AI request timed out |
285
+ | `AI_PROVIDER_UNAVAILABLE` | 503 | AI provider unavailable |
286
+ | `AI_CONTEXT_LENGTH_EXCEEDED` | 422 | AI context length exceeded |
287
+ | `AI_OUTPUT_INVALID` | 502 | Invalid AI model output |
288
+ | `MCP_ORIGIN_DENIED` | 403 | MCP origin denied |
289
+ | `MCP_INPUT_INVALID` | 400 | Invalid MCP tool input |
290
+ | `MCP_RESULT_TOO_LARGE` | 413 | MCP tool result too large |
291
+ | `MCP_RATE_LIMITED` | 429 | MCP rate limit exceeded |
292
+ | `PAYMENT_GATEWAY_UNKNOWN` | 500 | Payment gateway unknown |
293
+ | `PAYMENT_GATEWAY_FAILED` | 502 | Payment gateway request failed |
294
+ | `PAYMENT_GATEWAY_UNAVAILABLE` | 503 | Payment gateway unavailable |
295
+ | `PAYMENT_REQUEST_INVALID` | 400 | Invalid payment request |
296
+ | `PAYMENT_CAPABILITY_UNSUPPORTED` | 501 | Payment capability not supported by the gateway |
297
+ | `PAYMENT_DECLINED` | 402 | Payment declined |
298
+ | `PAYMENT_NOT_FOUND` | 404 | Payment not found |
299
+ | `PAYMENT_INVALID_STATE` | 409 | Invalid payment state |
300
+ | `PAYMENT_AMOUNT_INVALID` | 400 | Invalid payment amount |
301
+ | `PAYMENT_CURRENCY_UNSUPPORTED` | 400 | Payment currency not supported |
302
+ | `PAYMENT_REFUND_EXCEEDED` | 409 | Refund exceeds the refundable amount |
303
+ | `PAYMENT_METHOD_NOT_FOUND` | 404 | Payment method not found |
304
+ | `PAYMENT_PLAN_UNKNOWN` | 404 | Payment plan unknown |
305
+ | `PAYMENT_SUBSCRIPTION_NOT_FOUND` | 404 | Subscription not found |
306
+ | `PAYMENT_SUBSCRIPTIONS_DISABLED` | 501 | Subscriptions disabled |
307
+ | `PAYMENT_WEBHOOK_INVALID` | 400 | Invalid payment webhook |
308
+
309
+ `REQUEST_FAILED` keeps the 4xx status of an error a Fastify plugin raised with no code of its own.
310
+
311
+ The `PAYMENT_*` codes and their `details` (the `gateway`, the `declineCode` of a refused card, the `refundable`
312
+ amount) are described with the [payments](./payments.md#errors).
313
+
314
+ ## Throwing errors in the application
315
+
316
+ Throw the framework error that fits from a service hook, a policy or a custom route, so the response and the OpenAPI
317
+ documentation stay consistent:
318
+
319
+ ```ts
320
+ import { ErrorCode, RequestError } from '@appweaver/common';
321
+ import { ResourceError } from '@appweaver/common';
322
+ import { createPolicy, createService } from '@appweaver/data';
323
+
324
+ export default createService({
325
+ modelName: 'Position',
326
+ beforeCreate: (data) => {
327
+ if (data.salaryMin > data.salaryMax) {
328
+ throw new RequestError(
329
+ ErrorCode.ValidationFailed,
330
+ 'salaryMin cannot exceed salaryMax',
331
+ {
332
+ errors: [
333
+ {
334
+ field: 'salaryMin',
335
+ rule: 'max',
336
+ message: 'cannot exceed salaryMax'
337
+ }
338
+ ]
339
+ }
340
+ );
341
+ }
342
+ }
343
+ });
344
+
345
+ export const policy = createPolicy({
346
+ modelName: 'User',
347
+ writeRestrictions: (user, data, action) => {
348
+ if (user && data.id !== user.id) {
349
+ throw new ResourceError(
350
+ ErrorCode.ResourceForbidden,
351
+ 'Only the own profile can be changed',
352
+ {
353
+ model: 'User',
354
+ action
355
+ }
356
+ );
357
+ }
358
+ return null;
359
+ }
360
+ });
361
+ ```
362
+
363
+ Leave the unique and the other constraints to the database: the resource services translate a violation into a
364
+ `DatabaseError` naming the model fields (a foreign key column as its relation, i.e. `author` for `authorId`), so
365
+ there is no need to look a value up before creating a record. A record removed after it was read, i.e. by a
366
+ concurrent delete, is a `RESOURCE_NOT_FOUND` of the service. Code calling the Prisma client directly translates its
367
+ errors the same way with `toDatabaseError`, which returns any other error as it is:
368
+
369
+ ```ts
370
+ import { toDatabaseError } from '@appweaver/data';
371
+
372
+ try {
373
+ await db.order.update({ where: { id }, data });
374
+ } catch (e) {
375
+ throw toDatabaseError(e, 'Order'); // i.e. DATABASE_RECORD_NOT_FOUND
376
+ }
377
+ ```
378
+
379
+ ### Application error codes
380
+
381
+ Register the errors of the application with `defineErrors`, which maps each to its HTTP status and title, and throw
382
+ them with an `ApplicationError`. The errors are named in PascalCase like the members of `ErrorCode`, and the code of
383
+ each is derived from its name, i.e. `OUT_OF_STOCK` for `OutOfStock` (typed as that literal), unless the mapping gives
384
+ one with `code`. Define them in a module of their own and import the returned codes where they are used, so they are
385
+ registered before any route documents them:
386
+
387
+ ```ts
388
+ // src/errors.ts
389
+ import { defineErrors } from '@appweaver/common';
390
+
391
+ export const ShopErrors = defineErrors({
392
+ OutOfStock: { status: 409, title: 'Product out of stock' },
393
+ CouponInvalid: { status: 400, title: 'Invalid coupon' }
394
+ });
395
+ ```
396
+
397
+ ```ts
398
+ import { ApplicationError } from '@appweaver/common';
399
+ import { ShopErrors } from '@/errors';
400
+
401
+ throw new ApplicationError(
402
+ ShopErrors.OutOfStock,
403
+ `Only ${product.stock} left of ${product.name}`,
404
+ {
405
+ productId: product.id
406
+ }
407
+ );
408
+ ```
409
+
410
+ A name not in PascalCase, a name or a code of the framework, one registered again with another mapping, or a status
411
+ outside 400-599 is rejected with a `ConfigurationError`. The OpenAPI specification names the members of its error code
412
+ enum after them (`x-enum-varnames`), so the generated client declares `ErrorCode.OutOfStock` the same way as
413
+ `ErrorCode.ResourceNotFound`. An `ApplicationError` with an unregistered code responds with a 500 status and logs a
414
+ warning.
415
+
416
+ ## Documenting the errors of a route
417
+
418
+ Every route of the framework documents the errors it can respond with, one response per status narrowing the `code` of
419
+ the `ProblemDetails` schema to the codes of that status. Custom routes do the same with `errorResponses`, which always
420
+ adds the validation, malformed request, rate limit and internal errors, and `registerRoute` adds the authentication,
421
+ reCAPTCHA and Turnstile errors of the route:
422
+
423
+ ```ts
424
+ import { ErrorCode } from '@appweaver/common';
425
+ import { errorResponses, registerRoute } from '@appweaver/web';
426
+ import { ShopErrors } from '@/errors';
427
+
428
+ registerRoute((router) => {
429
+ router.post(
430
+ '/checkout',
431
+ {
432
+ schema: {
433
+ response: {
434
+ 201: Type.Ref('OrderSingle'),
435
+ ...errorResponses(
436
+ ShopErrors.OutOfStock,
437
+ ShopErrors.CouponInvalid,
438
+ ErrorCode.ResourceNotFound
439
+ )
440
+ }
441
+ }
442
+ },
443
+ handler
444
+ );
445
+ });
446
+ ```
447
+
448
+ `errorResponses` rejects a code that is not registered. The route itself declares a `4xx` and a `5xx` response referring
449
+ to the `ProblemDetails` schema, listing the codes of each status in the `x-appweaver-errors` extension. The server
450
+ moves them out of the route before compiling its serializers, since the error handler builds the problem details itself,
451
+ which keeps the start of the server fast. The OpenAPI document expands them into a response per status narrowing the
452
+ `code` to its codes, and shares the identical ones between the operations under `components.responses`, each
453
+ operation referring to them. A response of a single code is named after it (i.e. `ResourceNotFoundError`), and one of
454
+ several after its status and a hash of its codes (i.e. `BadRequestError_1a2b3c`), so a name changes only with its own
455
+ codes.
456
+
457
+ The `code` of the `ProblemDetails` schema is an enum of every framework code and every application code registered
458
+ with `defineErrors` before the server is created, i.e. by the application modules. The generated client exports it as
459
+ `ErrorCode`, with `isApiError` and `client.isRouteError` typing a caught error by the codes of the API or of a route
460
+ (see [client.md](./client.md#error-handling)).
461
+
462
+ ## Handling errors outside the API
463
+
464
+ A queue worker, a scheduled job or a script catches the errors by their code:
465
+
466
+ ```ts
467
+ import { ErrorCode, isAppweaverError } from '@appweaver/common';
468
+
469
+ try {
470
+ await injectService('Order').update(id, { status: 'Shipped' });
471
+ } catch (e) {
472
+ if (isAppweaverError(e) && e.is(ErrorCode.DatabaseWriteConflict)) {
473
+ // retry
474
+ }
475
+ throw e;
476
+ }
477
+ ```
478
+
479
+ The `retries` option of `runTransaction` retries the `DATABASE_WRITE_CONFLICT` errors itself.
480
+
481
+ ## Adding a framework error code
482
+
483
+ 1. Add the member to `ErrorCode` in `packages/common/errors/error-code.ts`, prefixed with its module.
484
+ 2. Add its details to `ErrorDetailsMap` in `packages/common/errors/error-details.ts`, unless it carries none.
485
+ 3. Map it in `errorHttpMap` of `packages/web/errors/error-http-map.ts` (a missing mapping fails to compile).
486
+ 4. List it in the `errorResponses` of the routes that can respond with it, and in the table above.