@terreno/api 0.27.0 → 0.28.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/dist/actions.test.js +2 -1
- package/dist/api.coverage.test.js +4 -2
- package/dist/api.errorPaths.test.js +5 -3
- package/dist/api.errors.test.js +6 -7
- package/dist/api.hooks.test.js +65 -8
- package/dist/api.js +93 -47
- package/dist/api.test.js +10 -4
- package/dist/auth.test.js +1 -1
- package/dist/config.js +7 -4
- package/dist/config.test.js +28 -3
- package/dist/docLoader.js +15 -51
- package/dist/docLoader.test.js +2 -1
- package/dist/errors.d.ts +72 -5
- package/dist/errors.js +265 -67
- package/dist/errors.test.js +163 -13
- package/dist/httpClient.d.ts +2 -3
- package/dist/httpClient.js +4 -4
- package/dist/httpClient.test.js +3 -2
- package/dist/notifiers/googleChatNotifier.test.js +2 -1
- package/dist/notifiers/slackNotifier.test.js +1 -1
- package/dist/notifiers/zoomNotifier.test.js +2 -1
- package/dist/permissions.js +0 -2
- package/dist/permissions.middleware.test.js +7 -42
- package/dist/plugins.test.js +4 -2
- package/dist/transformers.js +4 -2
- package/package.json +2 -2
- package/src/actions.test.ts +2 -1
- package/src/api.coverage.test.ts +4 -2
- package/src/api.errorPaths.test.ts +5 -3
- package/src/api.errors.test.ts +6 -7
- package/src/api.hooks.test.ts +24 -1
- package/src/api.test.ts +10 -4
- package/src/api.ts +93 -48
- package/src/auth.test.ts +1 -1
- package/src/config.test.ts +25 -3
- package/src/config.ts +7 -4
- package/src/docLoader.test.ts +2 -1
- package/src/docLoader.ts +16 -18
- package/src/errors.test.ts +178 -13
- package/src/errors.ts +278 -79
- package/src/httpClient.test.ts +3 -2
- package/src/httpClient.ts +4 -4
- package/src/notifiers/googleChatNotifier.test.ts +2 -2
- package/src/notifiers/slackNotifier.test.ts +2 -2
- package/src/notifiers/zoomNotifier.test.ts +2 -2
- package/src/permissions.middleware.test.ts +7 -11
- package/src/permissions.ts +0 -2
- package/src/plugins.test.ts +4 -2
- package/src/transformers.ts +4 -2
- package/tsconfig.json +1 -1
package/src/errors.ts
CHANGED
|
@@ -5,9 +5,53 @@ import mongoose, {Schema} from "mongoose";
|
|
|
5
5
|
|
|
6
6
|
import {logger} from "./logger";
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
// Maps common HTTP statuses to a standard Error name so external tools (Sentry, log explorers)
|
|
9
|
+
// show a meaningful error type instead of a generic "APIError".
|
|
10
|
+
const STATUS_ERROR_NAMES: {[status: number]: string} = {
|
|
11
|
+
400: "BadRequestError",
|
|
12
|
+
401: "UnauthorizedError",
|
|
13
|
+
403: "ForbiddenError",
|
|
14
|
+
404: "NotFoundError",
|
|
15
|
+
405: "MethodNotAllowedError",
|
|
16
|
+
409: "ConflictError",
|
|
17
|
+
410: "GoneError",
|
|
18
|
+
412: "PreconditionFailedError",
|
|
19
|
+
413: "PayloadTooLargeError",
|
|
20
|
+
415: "UnsupportedMediaTypeError",
|
|
21
|
+
422: "ValidationError",
|
|
22
|
+
429: "TooManyRequestsError",
|
|
23
|
+
500: "InternalServerError",
|
|
24
|
+
501: "NotImplementedError",
|
|
25
|
+
502: "BadGatewayError",
|
|
26
|
+
503: "ServiceUnavailableError",
|
|
27
|
+
504: "GatewayTimeoutError",
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
// Converts an application error code like "update-admin-error" into a PascalCase Error name
|
|
31
|
+
// like "UpdateAdminError" so each logical error gets its own type in external tools.
|
|
32
|
+
const errorNameFromCode = (code: string): string | undefined => {
|
|
33
|
+
const words = code.split(/[^a-zA-Z0-9]+/).filter(Boolean);
|
|
34
|
+
if (words.length === 0) {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
return words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const normalizeStatus = (status: number | undefined): number => {
|
|
41
|
+
if (status === undefined || status === null) {
|
|
42
|
+
return 500;
|
|
43
|
+
}
|
|
44
|
+
const truncated = Math.trunc(status);
|
|
45
|
+
if (!Number.isFinite(truncated) || truncated < 400 || truncated > 599) {
|
|
46
|
+
return 500;
|
|
47
|
+
}
|
|
48
|
+
return truncated;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export interface APIErrorOptions {
|
|
9
52
|
// Required. A short, human-readable summary of the problem that SHOULD NOT change from
|
|
10
53
|
// occurrence to occurrence of the problem, except for purposes of localization.
|
|
54
|
+
// Becomes the standard `Error.message`.
|
|
11
55
|
title: string;
|
|
12
56
|
|
|
13
57
|
// error messages to be displayed by a field in a form. this isn't in the JSONAPI spec.
|
|
@@ -21,11 +65,12 @@ export interface APIErrorConstructor {
|
|
|
21
65
|
links?: {about?: string; type?: string} | undefined;
|
|
22
66
|
// The HTTP status code applicable to this problem. defaults to 500. must be between 400 and 599.
|
|
23
67
|
status?: number;
|
|
24
|
-
// An application-specific error code, expressed as a string value.
|
|
68
|
+
// An application-specific error code, expressed as a string value (kebab-case recommended).
|
|
69
|
+
// Also drives the standard `Error.name` (e.g. "update-admin-error" -> "UpdateAdminError").
|
|
25
70
|
code?: string;
|
|
26
71
|
|
|
27
72
|
// A human-readable explanation specific to this occurrence of the problem. Like title,
|
|
28
|
-
// this field’s value can be localized.
|
|
73
|
+
// this field’s value can be localized. Unlike title, it is NOT folded into `Error.message`.
|
|
29
74
|
detail?: string;
|
|
30
75
|
// An object containing references to the source of the error,
|
|
31
76
|
// optionally including any of the following members:
|
|
@@ -41,9 +86,32 @@ export interface APIErrorConstructor {
|
|
|
41
86
|
header?: string;
|
|
42
87
|
};
|
|
43
88
|
// A meta object containing non-standard meta-information about the error.
|
|
44
|
-
meta?: {[id: string]:
|
|
89
|
+
meta?: {[id: string]: unknown};
|
|
90
|
+
// The original error being wrapped, exposed as the standard ES2022 `Error.cause` so external
|
|
91
|
+
// tools (e.g. Sentry linked exceptions) can display the original error with its own stack.
|
|
92
|
+
cause?: unknown;
|
|
93
|
+
/** @deprecated Use `cause` instead. Kept as an alias for backwards compatibility. */
|
|
45
94
|
error?: unknown;
|
|
46
95
|
// If true, this error will not be sent to external error reporting tools like Sentry.
|
|
96
|
+
// Never serialized to clients.
|
|
97
|
+
disableExternalErrorTracking?: boolean;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** @deprecated Use {@link APIErrorOptions} instead. */
|
|
101
|
+
export type APIErrorConstructor = APIErrorOptions;
|
|
102
|
+
|
|
103
|
+
// The client-facing JSONAPI error body. Standard Error fields (name, stack, cause) are
|
|
104
|
+
// intentionally excluded. disableExternalErrorTracking is included when true so clients can
|
|
105
|
+
// suppress duplicate Sentry reporting for expected errors.
|
|
106
|
+
export interface APIErrorBody {
|
|
107
|
+
status: number;
|
|
108
|
+
title: string;
|
|
109
|
+
id?: string;
|
|
110
|
+
links?: {about?: string; type?: string};
|
|
111
|
+
code?: string;
|
|
112
|
+
detail?: string;
|
|
113
|
+
source?: {pointer?: string; parameter?: string; header?: string};
|
|
114
|
+
meta?: {[id: string]: unknown};
|
|
47
115
|
disableExternalErrorTracking?: boolean;
|
|
48
116
|
}
|
|
49
117
|
|
|
@@ -52,6 +120,12 @@ export interface APIErrorConstructor {
|
|
|
52
120
|
* HTTP code displayed. It follows the JSONAPI spec to standardize the fields,
|
|
53
121
|
* allowing the UI to show more consistent, better error messages.
|
|
54
122
|
*
|
|
123
|
+
* It uses the standard `Error` fields the way external tools (e.g. Sentry) expect:
|
|
124
|
+
* - `message` is exactly `title` — a stable, human-readable summary of the problem type.
|
|
125
|
+
* - `name` is the error type, derived from the subclass name, `code`, or `status`
|
|
126
|
+
* (e.g. a 404 becomes "NotFoundError").
|
|
127
|
+
* - `cause` holds the wrapped original error, so linked exceptions keep their own stack.
|
|
128
|
+
*
|
|
55
129
|
* ```ts
|
|
56
130
|
* throw new APIError({
|
|
57
131
|
* title: "Only an admin can update that!",
|
|
@@ -62,7 +136,9 @@ export interface APIErrorConstructor {
|
|
|
62
136
|
* ```
|
|
63
137
|
*/
|
|
64
138
|
export class APIError extends Error {
|
|
65
|
-
|
|
139
|
+
// Brand for detection across duplicate copies of @terreno/api in node_modules, where
|
|
140
|
+
// `instanceof` checks fail. See isAPIError.
|
|
141
|
+
readonly isTerrenoAPIError = true;
|
|
66
142
|
|
|
67
143
|
id: string | undefined;
|
|
68
144
|
|
|
@@ -84,48 +160,122 @@ export class APIError extends Error {
|
|
|
84
160
|
|
|
85
161
|
meta: {[id: string]: unknown} | undefined;
|
|
86
162
|
|
|
87
|
-
error?: unknown;
|
|
88
|
-
|
|
89
163
|
disableExternalErrorTracking?: boolean;
|
|
90
164
|
|
|
91
|
-
constructor(
|
|
92
|
-
const
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
165
|
+
constructor(options: APIErrorOptions) {
|
|
166
|
+
const cause = options.cause ?? options.error;
|
|
167
|
+
// message is exactly the stable title; detail and cause stacks are separate fields.
|
|
168
|
+
super(options.title, cause === undefined ? undefined : {cause});
|
|
169
|
+
// The package compiles to ES5, where extending built-ins loses the prototype chain (the
|
|
170
|
+
// original reason isAPIError checked `name` instead of using `instanceof`). Repair it so
|
|
171
|
+
// getters, methods, and instanceof work on compiled output too.
|
|
172
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
173
|
+
|
|
174
|
+
this.status = normalizeStatus(options.status);
|
|
175
|
+
this.code = options.code;
|
|
176
|
+
// name precedence: subclass name (from new.target) > code > status-derived > "APIError".
|
|
177
|
+
const subclassName =
|
|
178
|
+
new.target !== APIError && new.target.name && new.target.name !== "APIError"
|
|
179
|
+
? new.target.name
|
|
180
|
+
: undefined;
|
|
181
|
+
this.name =
|
|
182
|
+
subclassName ??
|
|
183
|
+
(options.code ? errorNameFromCode(options.code) : undefined) ??
|
|
184
|
+
STATUS_ERROR_NAMES[this.status] ??
|
|
185
|
+
"APIError";
|
|
186
|
+
|
|
187
|
+
this.id = options.id;
|
|
188
|
+
this.links = options.links;
|
|
189
|
+
this.detail = options.detail;
|
|
190
|
+
this.source = options.source;
|
|
191
|
+
this.meta = options.meta ?? {};
|
|
192
|
+
this.disableExternalErrorTracking = options.disableExternalErrorTracking;
|
|
193
|
+
if (options.fields) {
|
|
194
|
+
this.meta.fields = options.fields;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** @deprecated Use the standard `cause` field instead. */
|
|
199
|
+
get error(): unknown {
|
|
200
|
+
return this.cause;
|
|
201
|
+
}
|
|
97
202
|
|
|
98
|
-
|
|
203
|
+
// JSONAPI title is the same stable summary as the standard Error message. A getter keeps the
|
|
204
|
+
// two from ever drifting.
|
|
205
|
+
get title(): string {
|
|
206
|
+
return this.message;
|
|
207
|
+
}
|
|
99
208
|
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
209
|
+
// Client-facing JSONAPI body. Excludes name/stack/cause; includes
|
|
210
|
+
// disableExternalErrorTracking only when true (client Sentry suppression).
|
|
211
|
+
toJSON(): APIErrorBody {
|
|
212
|
+
return serializeAPIError(this);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// Convenience subclasses for the most common statuses. They are sugar only — everything works
|
|
217
|
+
// with plain APIError.
|
|
218
|
+
|
|
219
|
+
/** Options accepted by the status-specific APIError subclasses: a title string or full options. */
|
|
220
|
+
export type APIErrorSubclassOptions = Omit<APIErrorOptions, "status"> | string;
|
|
221
|
+
|
|
222
|
+
const withStatus = (options: APIErrorSubclassOptions, status: number): APIErrorOptions => {
|
|
223
|
+
return typeof options === "string" ? {status, title: options} : {...options, status};
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
/** 400 Bad Request. */
|
|
227
|
+
export class BadRequestError extends APIError {
|
|
228
|
+
constructor(options: APIErrorSubclassOptions) {
|
|
229
|
+
super(withStatus(options, 400));
|
|
230
|
+
this.name = "BadRequestError";
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** 401 Unauthorized. */
|
|
235
|
+
export class UnauthorizedError extends APIError {
|
|
236
|
+
constructor(options: APIErrorSubclassOptions) {
|
|
237
|
+
super(withStatus(options, 401));
|
|
238
|
+
this.name = "UnauthorizedError";
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** 403 Forbidden. */
|
|
243
|
+
export class ForbiddenError extends APIError {
|
|
244
|
+
constructor(options: APIErrorSubclassOptions) {
|
|
245
|
+
super(withStatus(options, 403));
|
|
246
|
+
this.name = "ForbiddenError";
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** 404 Not Found. */
|
|
251
|
+
export class NotFoundError extends APIError {
|
|
252
|
+
constructor(options: APIErrorSubclassOptions) {
|
|
253
|
+
super(withStatus(options, 404));
|
|
254
|
+
this.name = "NotFoundError";
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** 409 Conflict. */
|
|
259
|
+
export class ConflictError extends APIError {
|
|
260
|
+
constructor(options: APIErrorSubclassOptions) {
|
|
261
|
+
super(withStatus(options, 409));
|
|
262
|
+
this.name = "ConflictError";
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** 400 Bad Request with a "ValidationError" type, for request/schema validation failures. */
|
|
267
|
+
export class ValidationError extends APIError {
|
|
268
|
+
constructor(options: APIErrorSubclassOptions) {
|
|
269
|
+
super(withStatus(options, 400));
|
|
270
|
+
this.name = "ValidationError";
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** 500 Internal Server Error. */
|
|
275
|
+
export class InternalServerError extends APIError {
|
|
276
|
+
constructor(options: APIErrorSubclassOptions) {
|
|
277
|
+
super(withStatus(options, 500));
|
|
278
|
+
this.name = "InternalServerError";
|
|
129
279
|
}
|
|
130
280
|
}
|
|
131
281
|
|
|
@@ -167,7 +317,18 @@ export const errorsPlugin = (schema: Schema): void => {
|
|
|
167
317
|
};
|
|
168
318
|
|
|
169
319
|
export const isAPIError = (error: unknown): error is APIError => {
|
|
170
|
-
|
|
320
|
+
if (error instanceof APIError) {
|
|
321
|
+
return true;
|
|
322
|
+
}
|
|
323
|
+
if (error instanceof Error) {
|
|
324
|
+
// Brand check survives duplicate copies of @terreno/api in node_modules; the name check is a
|
|
325
|
+
// transition fallback for instances from older versions of the package.
|
|
326
|
+
return (
|
|
327
|
+
(error as {isTerrenoAPIError?: boolean}).isTerrenoAPIError === true ||
|
|
328
|
+
error.name === "APIError"
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
return false;
|
|
171
332
|
};
|
|
172
333
|
|
|
173
334
|
/** Extract a human-readable message from an unknown error. */
|
|
@@ -203,27 +364,46 @@ export const getDisableExternalErrorTracking = (error: unknown): boolean | undef
|
|
|
203
364
|
return undefined;
|
|
204
365
|
};
|
|
205
366
|
|
|
206
|
-
//
|
|
207
|
-
//
|
|
208
|
-
|
|
209
|
-
export const getAPIErrorBody = (error: APIError): Record<string, unknown> => {
|
|
210
|
-
const errorData: Record<string, unknown> = {status: error.status, title: error.title};
|
|
367
|
+
// Builds the client-facing JSONAPI body from any APIError-shaped error, including instances from
|
|
368
|
+
// older/duplicate copies of @terreno/api that may not have toJSON.
|
|
369
|
+
const serializeAPIError = (error: APIError): APIErrorBody => {
|
|
211
370
|
const indexable = error as unknown as Record<string, unknown>;
|
|
212
|
-
for
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
"
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
"
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
371
|
+
// Prefer an explicit title property for legacy/duplicate-package instances whose message was
|
|
372
|
+
// polluted with detail/cause stacks but still carry a clean title field.
|
|
373
|
+
const title =
|
|
374
|
+
typeof indexable.title === "string" && indexable.title.length > 0
|
|
375
|
+
? indexable.title
|
|
376
|
+
: error.message;
|
|
377
|
+
const body: Record<string, unknown> = {
|
|
378
|
+
status: typeof indexable.status === "number" ? indexable.status : 500,
|
|
379
|
+
title,
|
|
380
|
+
};
|
|
381
|
+
for (const key of ["id", "links", "code", "detail", "source", "meta"]) {
|
|
382
|
+
const value = indexable[key];
|
|
383
|
+
if (
|
|
384
|
+
key === "meta" &&
|
|
385
|
+
value &&
|
|
386
|
+
typeof value === "object" &&
|
|
387
|
+
Object.keys(value as object).length === 0
|
|
388
|
+
) {
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
if (value) {
|
|
392
|
+
body[key] = value;
|
|
224
393
|
}
|
|
225
394
|
}
|
|
226
|
-
|
|
395
|
+
if (indexable.disableExternalErrorTracking === true) {
|
|
396
|
+
body.disableExternalErrorTracking = true;
|
|
397
|
+
}
|
|
398
|
+
return body as unknown as APIErrorBody;
|
|
399
|
+
};
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* Creates an APIError body to send to clients as JSON.
|
|
403
|
+
* @deprecated Use `error.toJSON()` instead.
|
|
404
|
+
*/
|
|
405
|
+
export const getAPIErrorBody = (error: APIError): Record<string, unknown> => {
|
|
406
|
+
return serializeAPIError(error) as unknown as Record<string, unknown>;
|
|
227
407
|
};
|
|
228
408
|
|
|
229
409
|
export const apiUnauthorizedMiddleware = (
|
|
@@ -249,24 +429,24 @@ export const mongooseErrorToAPIError = (err: Error): APIError | null => {
|
|
|
249
429
|
for (const [path, subErr] of Object.entries(err.errors)) {
|
|
250
430
|
fields[path] = subErr.message;
|
|
251
431
|
}
|
|
252
|
-
return new
|
|
432
|
+
return new ValidationError({
|
|
433
|
+
cause: err,
|
|
253
434
|
detail: err.message,
|
|
254
435
|
disableExternalErrorTracking: true,
|
|
255
436
|
fields,
|
|
256
|
-
status: 400,
|
|
257
437
|
title: "Validation failed",
|
|
258
438
|
});
|
|
259
439
|
}
|
|
260
440
|
|
|
261
441
|
if (err instanceof mongoose.Error.CastError) {
|
|
262
442
|
const path = err.path ?? "field";
|
|
263
|
-
return new
|
|
443
|
+
return new ValidationError({
|
|
444
|
+
cause: err,
|
|
264
445
|
detail: `Invalid value for ${path}`,
|
|
265
446
|
disableExternalErrorTracking: true,
|
|
266
447
|
fields: {
|
|
267
448
|
[path]: `Expected ${err.kind ?? "a valid value"}, got ${JSON.stringify(err.value)}`,
|
|
268
449
|
},
|
|
269
|
-
status: 400,
|
|
270
450
|
title: "Validation failed",
|
|
271
451
|
});
|
|
272
452
|
}
|
|
@@ -274,27 +454,46 @@ export const mongooseErrorToAPIError = (err: Error): APIError | null => {
|
|
|
274
454
|
return null;
|
|
275
455
|
};
|
|
276
456
|
|
|
457
|
+
// Logs the error (warn for 4xx client errors, error for 5xx server errors) and captures it with
|
|
458
|
+
// Sentry unless external tracking is disabled. Fingerprints on the logical error type
|
|
459
|
+
// (name + code/title + status) so unrelated errors constructed at the same framework lines don't
|
|
460
|
+
// group together, while the `cause` chain preserves each occurrence's real origin stack.
|
|
461
|
+
const logAndCaptureAPIError = (err: APIError): void => {
|
|
462
|
+
const cause = err.cause;
|
|
463
|
+
const causeStack = cause instanceof Error && cause.stack ? `\n${cause.stack}` : "";
|
|
464
|
+
const logMessage = `${err.name}(${err.status}): ${err.message}${
|
|
465
|
+
err.detail ? ` — ${err.detail}` : ""
|
|
466
|
+
}${causeStack}`;
|
|
467
|
+
const logFn = err.status >= 500 ? logger.error.bind(logger) : logger.warn.bind(logger);
|
|
468
|
+
if (err.disableExternalErrorTracking) {
|
|
469
|
+
logFn(logMessage);
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
logFn(logMessage);
|
|
473
|
+
Sentry.withScope((scope) => {
|
|
474
|
+
scope.setFingerprint([err.name, err.code ?? err.name, String(err.status)]);
|
|
475
|
+
scope.setTag("http.status_code", String(err.status));
|
|
476
|
+
if (err.code) {
|
|
477
|
+
scope.setTag("api_error.code", err.code);
|
|
478
|
+
}
|
|
479
|
+
scope.setContext("apiError", serializeAPIError(err) as unknown as Record<string, unknown>);
|
|
480
|
+
Sentry.captureException(err);
|
|
481
|
+
});
|
|
482
|
+
};
|
|
483
|
+
|
|
277
484
|
export const apiErrorMiddleware = (
|
|
278
485
|
err: Error,
|
|
279
486
|
_req: Request,
|
|
280
487
|
res: Response,
|
|
281
488
|
next: NextFunction
|
|
282
489
|
) => {
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
}
|
|
287
|
-
res.status(err.status).json(getAPIErrorBody(err)).send();
|
|
288
|
-
return;
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
const mongooseError = mongooseErrorToAPIError(err);
|
|
292
|
-
if (mongooseError) {
|
|
293
|
-
res.status(mongooseError.status).json(getAPIErrorBody(mongooseError)).send();
|
|
490
|
+
const apiError = isAPIError(err) ? err : mongooseErrorToAPIError(err);
|
|
491
|
+
if (!apiError) {
|
|
492
|
+
next(err);
|
|
294
493
|
return;
|
|
295
494
|
}
|
|
296
|
-
|
|
297
|
-
|
|
495
|
+
logAndCaptureAPIError(apiError);
|
|
496
|
+
res.status(apiError.status).json(serializeAPIError(apiError)).send();
|
|
298
497
|
};
|
|
299
498
|
|
|
300
499
|
/**
|
package/src/httpClient.test.ts
CHANGED
|
@@ -226,7 +226,7 @@ describe("withApiErrorHandling", () => {
|
|
|
226
226
|
expect(normalized.classification).toBe("notFound");
|
|
227
227
|
});
|
|
228
228
|
|
|
229
|
-
it("converts to an APIError when rethrowAs is apiError
|
|
229
|
+
it("converts to an APIError when rethrowAs is apiError without logging itself", async () => {
|
|
230
230
|
const {logger, entries} = createRecordingLogger();
|
|
231
231
|
const original = buildAxiosError({data: {message: "Rate limit exceeded"}, status: 429});
|
|
232
232
|
let caught: unknown;
|
|
@@ -247,7 +247,8 @@ describe("withApiErrorHandling", () => {
|
|
|
247
247
|
expect(apiError.detail).toBe("Rate limit exceeded");
|
|
248
248
|
expect(apiError.error).toBe(original);
|
|
249
249
|
expect(apiError.meta?.classification).toBe("rateLimited");
|
|
250
|
-
//
|
|
250
|
+
// The wrapper stays silent — apiErrorMiddleware logs the APIError, so logging here
|
|
251
|
+
// too would produce two log entries for the same failure.
|
|
251
252
|
expect(entries).toHaveLength(0);
|
|
252
253
|
});
|
|
253
254
|
|
package/src/httpClient.ts
CHANGED
|
@@ -193,9 +193,8 @@ export interface WithApiErrorHandlingOptions {
|
|
|
193
193
|
*
|
|
194
194
|
* In "raw" mode (default) the wrapper logs the normalized shape via the injected logger
|
|
195
195
|
* and rethrows the original error. In "apiError" mode the wrapper throws a terreno
|
|
196
|
-
* APIError
|
|
197
|
-
*
|
|
198
|
-
* per-occurrence text goes in `detail`, built from the (redacted) normalized messages.
|
|
196
|
+
* APIError with a stable title (per-occurrence text goes in `detail`) and stays silent
|
|
197
|
+
* itself — apiErrorMiddleware logs APIErrors, so logging here too would double-log.
|
|
199
198
|
*/
|
|
200
199
|
export const withApiErrorHandling = async <T>(
|
|
201
200
|
fn: () => Promise<T>,
|
|
@@ -215,8 +214,9 @@ export const withApiErrorHandling = async <T>(
|
|
|
215
214
|
if (options.rethrowAs === "apiError") {
|
|
216
215
|
const statusCode = normalized.statusCode;
|
|
217
216
|
throw new APIError({
|
|
217
|
+
cause: error,
|
|
218
|
+
code: "http-client-error",
|
|
218
219
|
detail: normalized.messages[0] ?? "unknown error",
|
|
219
|
-
error,
|
|
220
220
|
meta: {classification: normalized.classification},
|
|
221
221
|
status: statusCode !== undefined && statusCode >= 400 ? statusCode : 500,
|
|
222
222
|
title: `${options.apiName} ${options.operation} request failed`,
|
|
@@ -3,7 +3,7 @@ import * as Sentry from "@sentry/bun";
|
|
|
3
3
|
import type {AxiosResponse} from "axios";
|
|
4
4
|
import axios from "axios";
|
|
5
5
|
|
|
6
|
-
import type
|
|
6
|
+
import {type APIError, isAPIError} from "../errors";
|
|
7
7
|
import {sendToGoogleChat} from "./googleChatNotifier";
|
|
8
8
|
|
|
9
9
|
describe("sendToGoogleChat", () => {
|
|
@@ -98,7 +98,7 @@ describe("sendToGoogleChat", () => {
|
|
|
98
98
|
await sendToGoogleChat("err", {shouldThrow: true});
|
|
99
99
|
throw new Error("Expected sendToGoogleChat to throw APIError");
|
|
100
100
|
} catch (error) {
|
|
101
|
-
expect((error
|
|
101
|
+
expect(isAPIError(error)).toBe(true);
|
|
102
102
|
expect((error as APIError).title).toMatch(/Error posting to Google Chat/i);
|
|
103
103
|
}
|
|
104
104
|
expect(mockAxiosPost.mock.calls.length).toBe(1);
|
|
@@ -2,7 +2,7 @@ import {afterAll, afterEach, beforeEach, describe, expect, it, type Mock, spyOn}
|
|
|
2
2
|
import * as Sentry from "@sentry/bun";
|
|
3
3
|
import axios from "axios";
|
|
4
4
|
|
|
5
|
-
import {APIError} from "../errors";
|
|
5
|
+
import {APIError, isAPIError} from "../errors";
|
|
6
6
|
import {sendToSlack} from "./slackNotifier";
|
|
7
7
|
|
|
8
8
|
describe("sendToSlack", () => {
|
|
@@ -121,7 +121,7 @@ describe("sendToSlack", () => {
|
|
|
121
121
|
throw new Error("Expected sendToSlack to throw APIError");
|
|
122
122
|
} catch (error) {
|
|
123
123
|
const apiError = error as APIError;
|
|
124
|
-
expect(apiError
|
|
124
|
+
expect(isAPIError(apiError)).toBe(true);
|
|
125
125
|
expect(apiError.title).toMatch(/Error posting to slack/i);
|
|
126
126
|
}
|
|
127
127
|
expect(mockAxiosPost.mock.calls.length).toBe(1);
|
|
@@ -3,7 +3,7 @@ import * as Sentry from "@sentry/bun";
|
|
|
3
3
|
import type {AxiosResponse} from "axios";
|
|
4
4
|
import axios from "axios";
|
|
5
5
|
|
|
6
|
-
import type
|
|
6
|
+
import {type APIError, isAPIError} from "../errors";
|
|
7
7
|
import {sendToZoom} from "./zoomNotifier";
|
|
8
8
|
|
|
9
9
|
describe("sendToZoom", () => {
|
|
@@ -190,7 +190,7 @@ describe("sendToZoom", () => {
|
|
|
190
190
|
await sendToZoom({body: "err", header: "err"}, {channel: "default", shouldThrow: true});
|
|
191
191
|
throw new Error("Expected sendToZoom to throw APIError");
|
|
192
192
|
} catch (error) {
|
|
193
|
-
expect((error
|
|
193
|
+
expect(isAPIError(error)).toBe(true);
|
|
194
194
|
expect((error as APIError).title).toMatch(/Error posting to Zoom/i);
|
|
195
195
|
}
|
|
196
196
|
expect(mockAxiosPost.mock.calls.length).toBe(1);
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
// noExplicitAny: test mock typing
|
|
2
2
|
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
3
|
-
import {describe, expect, it, mock
|
|
4
|
-
import * as Sentry from "@sentry/bun";
|
|
3
|
+
import {describe, expect, it, mock} from "bun:test";
|
|
5
4
|
import type express from "express";
|
|
6
5
|
|
|
7
6
|
import {APIError} from "./errors";
|
|
@@ -81,11 +80,11 @@ describe("permissionMiddleware", () => {
|
|
|
81
80
|
const [error] = (next as any).mock.calls[0];
|
|
82
81
|
expect(error).toBeInstanceOf(APIError);
|
|
83
82
|
expect(error.status).toBe(500);
|
|
84
|
-
expect(error.title).
|
|
83
|
+
expect(error.title).toBe("GET error");
|
|
84
|
+
expect(error.detail).toContain("GET failed on 507f1f77bcf86cd799439011");
|
|
85
85
|
});
|
|
86
86
|
|
|
87
|
-
it("
|
|
88
|
-
const captureMessageSpy = spyOn(Sentry, "captureMessage");
|
|
87
|
+
it("returns plain not found when document does not exist", async () => {
|
|
89
88
|
const model = {
|
|
90
89
|
collection: {findOne: mock(async () => null)},
|
|
91
90
|
findById: mock(() => ({exec: mock(async () => null)})),
|
|
@@ -100,14 +99,11 @@ describe("permissionMiddleware", () => {
|
|
|
100
99
|
next as any
|
|
101
100
|
);
|
|
102
101
|
|
|
103
|
-
expect(captureMessageSpy).toHaveBeenCalledWith(
|
|
104
|
-
"Document 507f1f77bcf86cd799439011 not found for model MockModel"
|
|
105
|
-
);
|
|
106
102
|
const [error] = (next as any).mock.calls[0];
|
|
107
103
|
expect(error).toBeInstanceOf(APIError);
|
|
108
104
|
expect(error.status).toBe(404);
|
|
109
|
-
expect(error.
|
|
110
|
-
|
|
105
|
+
expect(error.title).toBe("Document not found");
|
|
106
|
+
expect(error.detail).toContain("507f1f77bcf86cd799439011");
|
|
111
107
|
});
|
|
112
108
|
|
|
113
109
|
it("returns hidden reason metadata when document is deleted", async () => {
|
|
@@ -194,6 +190,6 @@ describe("permissionMiddleware", () => {
|
|
|
194
190
|
const [error] = (next as any).mock.calls[0];
|
|
195
191
|
expect(error).toBeInstanceOf(APIError);
|
|
196
192
|
expect(error.status).toBe(404);
|
|
197
|
-
expect(error.
|
|
193
|
+
expect(error.title).toBe("Document not found");
|
|
198
194
|
});
|
|
199
195
|
});
|
package/src/permissions.ts
CHANGED
|
@@ -6,7 +6,6 @@ import type {ModelRouterOptions, RESTMethod} from "./api";
|
|
|
6
6
|
import type {User} from "./auth";
|
|
7
7
|
import {loadDocOr404} from "./docLoader";
|
|
8
8
|
import {APIError} from "./errors";
|
|
9
|
-
import {logger} from "./logger";
|
|
10
9
|
|
|
11
10
|
export type PermissionMethod<T> = (
|
|
12
11
|
method: RESTMethod,
|
|
@@ -158,7 +157,6 @@ export const permissionMiddleware = <T>(
|
|
|
158
157
|
|
|
159
158
|
return next();
|
|
160
159
|
} catch (error) {
|
|
161
|
-
logger.error(`Permissions error: ${error instanceof Error ? error.message : error}`);
|
|
162
160
|
return next(error);
|
|
163
161
|
}
|
|
164
162
|
};
|
package/src/plugins.test.ts
CHANGED
|
@@ -507,14 +507,16 @@ describe("DateOnly", () => {
|
|
|
507
507
|
it("returns 404 with context for hidden document", async () => {
|
|
508
508
|
const doc = await StuffModel.create({deleted: true, name: "test"});
|
|
509
509
|
const res = await agent.get(`/stuff/${doc._id}`).expect(404);
|
|
510
|
-
expect(res.body.title).toBe(
|
|
510
|
+
expect(res.body.title).toBe("Document not found");
|
|
511
|
+
expect(res.body.detail).toContain(String(doc._id));
|
|
511
512
|
expect(res.body.meta).toEqual({deleted: "true"});
|
|
512
513
|
});
|
|
513
514
|
|
|
514
515
|
it("returns 404 without meta for missing document", async () => {
|
|
515
516
|
const nonExistentId = "507f1f77bcf86cd799439011";
|
|
516
517
|
const res = await agent.get(`/stuff/${nonExistentId}`).expect(404);
|
|
517
|
-
expect(res.body.title).toBe(
|
|
518
|
+
expect(res.body.title).toBe("Document not found");
|
|
519
|
+
expect(res.body.detail).toContain(nonExistentId);
|
|
518
520
|
expect(res.body.meta).toBeUndefined();
|
|
519
521
|
});
|
|
520
522
|
});
|
package/src/transformers.ts
CHANGED
|
@@ -173,9 +173,11 @@ export const defaultResponseHandler = async <T>(
|
|
|
173
173
|
} catch (error: unknown) {
|
|
174
174
|
const errorObj = error as Error;
|
|
175
175
|
throw new APIError({
|
|
176
|
-
|
|
176
|
+
cause: errorObj,
|
|
177
|
+
code: "serialization-error",
|
|
178
|
+
detail: errorObj.message,
|
|
177
179
|
status: 400,
|
|
178
|
-
title: `Error serializing ${method} response
|
|
180
|
+
title: `Error serializing ${method} response`,
|
|
179
181
|
});
|
|
180
182
|
}
|
|
181
183
|
};
|