forked from Shelf-nu/shelf.nu
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror.ts
More file actions
373 lines (347 loc) · 9.71 KB
/
error.ts
File metadata and controls
373 lines (347 loc) · 9.71 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
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
import { createId } from "@paralleldrive/cuid2";
import { Prisma } from "@prisma/client";
import type { PrismaClientKnownRequestError } from "@prisma/client/runtime/library";
import type { ValidationError } from "./http";
/**
* The goal of this custom error class is to normalize our errors.
*/
type SerializableValue = string | number | boolean | object | null | undefined;
export const VALIDATION_ERROR = "validationErrors";
/**
* Additional data to help us debug.
*/
export type AdditionalData =
| {
[key: string]: SerializableValue;
}
| {
[VALIDATION_ERROR]?: ValidationError<any> | undefined;
[key: string]: SerializableValue;
};
/**
* @param message The message intended for the user.
* @param title The title of the error, if any, for a modal, a toast, etc.
*
* Other params are for logging purposes and help us debug.
* @param label A label to help us debug and filter logs.
* @param cause The error that caused the rejection.
* @param additionalData Additional data to help us debug.
* @param shouldBeCaptured Whether we should capture this error or not.
*
*/
export type FailureReason = {
/**
* The error that caused the rejection, if any.
*/
cause: unknown | null;
/**
* A label to help us debug and filter logs.
*/
label:
| "Unknown"
// Related to our modules
| "Admin dashboard"
| "App layout"
| "Assets"
| "Asset Index Settings"
| "Auth"
| "Barcode"
| "Booking"
| "Booking Settings"
| "Category"
| "Crop image"
| "CSV"
| "Custody"
| "Custom fields"
| "Dashboard"
| "Email"
| "Healthcheck"
| "Image"
| "Invite"
| "User onboarding"
| "Location"
| "Notification"
| "Organization"
| "Permission"
| "QR"
| "Report"
| "Settings"
| "Working hours"
| "File storage"
| "Scan"
| "Scheduler"
| "Stripe"
| "Stripe webhook"
| "Subscription"
| "Tag"
| "Team"
| "Team Member"
| "Tier"
| "User"
| "User Contact"
| "Scanner"
| "SSO"
| "Kit"
| "Note"
// Other kinds of errors
| "DB"
| "Request validation"
| "DB constrain violation"
| "Dev error" // Error that should never happen in production because it's a developer mistake
| "Environment" // Related to the environment setup
| "Image Import"
| "Image Cache"
| "Asset Reminder"
| "Asset Scheduler" // Error related to the image import
| "Update";
/**
* The message intended for the user.
* You can add new lines using \n which will be parsed into paragraphs in the html
* Moveoer, you can add html to highlight strings
*/
message: string;
/**
* The title of the error, if any, for a modal, a toast, etc.
*/
title?: string;
/**
* Additional data to help us debug.
*
* **Do not put sensitive data here.** It will be logged and could be sent to Sentry.
*/
additionalData?: AdditionalData;
/**
* Whether we should capture this error or not.
*
* If not, it will be logged but not sent to Sentry.
*
* **Default is true**
*/
shouldBeCaptured?: boolean;
/**
* The traceId is a unique identifier for the error.
*
* It can be the Stripe event id or an random generated id.
*/
traceId?: string;
/**
* The HTTP status code to return.
*
* Add more status codes as needed: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
*/
status?:
| 200 // ok
| 204 // no content
| 400 // bad request
| 401 // unauthorized
| 403 // forbidden
| 404 // not found
| 405 // method not allowed
| 409 // conflict
| 500; // internal server error
};
export type ErrorLabel = FailureReason["label"];
/**
* A custom error class to normalize the error handling in our app.
*/
export class ShelfError extends Error {
readonly cause: FailureReason["cause"];
readonly label: FailureReason["label"];
readonly title: FailureReason["title"];
readonly additionalData: FailureReason["additionalData"];
readonly shouldBeCaptured: FailureReason["shouldBeCaptured"];
readonly status: FailureReason["status"];
traceId: FailureReason["traceId"];
constructor({
cause,
label,
message,
title,
additionalData,
shouldBeCaptured,
status,
traceId,
}: FailureReason) {
super();
this.name = "ShelfError";
this.cause = cause;
this.label = label;
this.message = message;
this.title = isLikeShelfError(cause) ? title || cause.title : title;
this.additionalData = additionalData;
this.shouldBeCaptured =
(isLikeShelfError(cause)
? shouldBeCaptured ?? cause.shouldBeCaptured
: shouldBeCaptured) ?? true;
this.status = isLikeShelfError(cause)
? status || cause.status || 500
: isNotFoundError(cause)
? 404
: status || 500;
this.traceId = traceId || createId();
}
}
/**
* This helper function is used to check if an error is an instance of `ShelfError` or an object that looks like an `ShelfError`.
*/
export function isLikeShelfError(cause: unknown): cause is ShelfError {
return (
cause instanceof ShelfError ||
(typeof cause === "object" &&
cause !== null &&
"label" in cause &&
"message" in cause)
);
}
/**
* This helper function is used to check if an error is an instance of `ShelfError` or an object that looks like an `ShelfError`.
*/
export function isNotFoundError(
cause: unknown
): cause is PrismaClientKnownRequestError {
return (
typeof cause === "object" &&
cause !== null &&
"code" in cause &&
cause.code === "P2025"
);
}
/**
* This function is used to check if the error is a zod validation error.
*/
export function isZodValidationError(cause: unknown) {
if (!isLikeShelfError(cause)) {
return false;
}
return cause.additionalData && "validationErrors" in cause.additionalData;
}
export function makeShelfError(
cause: unknown,
additionalData?: AdditionalData,
shouldBeCaptured: boolean = true
) {
if (isLikeShelfError(cause)) {
// copy the original error and fill in the maybe missing fields like status or traceId
return new ShelfError({
...cause,
additionalData: {
...cause.additionalData,
...additionalData,
},
shouldBeCaptured:
"shouldBeCaptured" in cause ? cause.shouldBeCaptured : shouldBeCaptured,
});
}
// 🤷♂️ We don't know what this error is, so we create a new default one.
return new ShelfError({
cause,
message: "Sorry, something went wrong.",
additionalData,
label: "Unknown",
shouldBeCaptured,
});
}
/* --------------------------------------------------------------------------- */
/* Pre made errors */
/* --------------------------------------------------------------------------- */
export type Options = Partial<
Pick<
FailureReason,
"additionalData" | "message" | "title" | "shouldBeCaptured"
>
>;
/**
* Error for when a method is not allowed.
*
* **By default, the error will not be captured.**
*
* If you want to capture the error, you can set the `shouldBeCaptured` option to `true`.
*/
export function notAllowedMethod(method: string, options?: Options) {
return new ShelfError({
shouldBeCaptured: false,
message: `"${method}" method is not allowed.`,
...options,
cause: null,
status: 405,
label: "Request validation",
});
}
/**
* Error for when a resource is not found.
*
* **By default, the error will not be captured.**
*
* If you want to capture the error, you can set the `shouldBeCaptured` option to `true`.
*/
export function badRequest(
message: string,
options?: Omit<Options, "message">
) {
return new ShelfError({
shouldBeCaptured: false,
...options,
cause: null,
message,
status: 400,
label: "Request validation",
});
}
/**
* Error for when a you could suspect a unique constraint violation.
*
* **By default, the error will not be captured if it is a constrain violation**
*
* If you want to capture all errors, you can set the `shouldBeCaptured` option to `true`.
*/
export function maybeUniqueConstraintViolation(
cause: unknown,
modelName: string,
options?: Options
) {
let message = `We could not create or update this ${modelName}. Please try again or contact support.`;
let shouldBeCaptured = false;
const validationErrors = {} as ValidationError<any>;
if (
cause instanceof Prisma.PrismaClientKnownRequestError &&
cause.code === "P2002"
) {
shouldBeCaptured = false;
// Extract the target field(s) from the Prisma error
const target = cause.meta?.target as string[] | undefined;
// Filter out organizational fields and clean up function-wrapped fields
const relevantFields = target
?.filter((field) => {
// Remove organizational/scoping fields
if (
field === "organizationId" ||
field === "userId" ||
field === "teamId"
) {
return false;
}
return true;
})
.map((field) => {
// Clean up function-wrapped fields like 'lower(name)' -> 'name'
const match = field.match(/^[a-zA-Z_]+\(([^)]+)\)$/);
return match ? match[1] : field;
});
const failedField = relevantFields?.[0] || "name"; // Get the first relevant field or default to "name"
// Generate dynamic message based on the actual failed field
message = `${modelName} ${failedField} is already taken. Please choose a different ${failedField}.`;
validationErrors[failedField] = { message };
}
return new ShelfError({
cause,
shouldBeCaptured,
...options,
message,
additionalData: {
modelName,
...(options && options.additionalData),
validationErrors,
},
label: "DB constrain violation",
});
}