-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
zod-errors.test.ts
115 lines (99 loc) · 2.79 KB
/
zod-errors.test.ts
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
import type { Event, EventHint } from '@sentry/types';
import { applyZodErrorsToEvent } from '../src/index';
// Simplified type definition
interface ZodIssue {
code: string;
path: (string | number)[];
expected?: string | number;
received?: string | number;
keys?: string[];
message?: string;
}
class ZodError extends Error {
issues: ZodIssue[] = [];
// Eslint disabled to match what exists in Zod
// https://github.com/colinhacks/zod/blob/8910033b861c842df59919e7d45e7f51cf8b76a2/src/ZodError.ts#L199C1-L211C4
constructor(issues: ZodIssue[]) {
super();
const actualProto = new.target.prototype;
if (Object.setPrototypeOf) {
Object.setPrototypeOf(this, actualProto);
} else {
(this as any).__proto__ = actualProto;
}
this.name = 'ZodError';
this.issues = issues;
}
get errors() {
return this.issues;
}
static create = (issues: ZodIssue[]) => {
const error = new ZodError(issues);
return error;
};
flatten() {
const fieldErrors: any = {};
const formErrors: any[] = [];
for (const sub of this.issues) {
if (sub.path.length > 0) {
fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
fieldErrors[sub.path[0]].push(sub);
} else {
formErrors.push(sub);
}
}
return { formErrors, fieldErrors };
}
}
describe('applyZodErrorsToEvent()', () => {
test('should not do anything if exception is not a ZodError', () => {
const event: Event = {};
const eventHint: EventHint = { originalException: new Error() };
applyZodErrorsToEvent(100, event, eventHint);
// no changes
expect(event).toStrictEqual({});
});
test('should add ZodError issues to extras and format message', () => {
const issues = [
{
code: 'invalid_type',
expected: 'string',
received: 'number',
path: ['names', 1],
keys: ['extra'],
message: 'Invalid input: expected string, received number',
},
] satisfies ZodIssue[];
const originalException = ZodError.create(issues);
const event: Event = {
exception: {
values: [
{
type: 'Error',
value: originalException.message,
},
],
},
};
const eventHint: EventHint = { originalException };
const processedEvent = applyZodErrorsToEvent(100, event, eventHint);
expect(processedEvent.exception).toStrictEqual({
values: [
{
type: 'Error',
value: 'Failed to validate keys: names',
},
],
});
expect(processedEvent.extra).toStrictEqual({
'zoderror.issues': [
{
...issues[0],
path: issues[0].path.join('.'),
keys: JSON.stringify(issues[0].keys),
unionErrors: undefined,
},
],
});
});
});