Skip to content

Commit 834fe45

Browse files
committed
ensureError: convert ZodError to ZodRealError.
1 parent 1ccffa0 commit 834fe45

3 files changed

Lines changed: 27 additions & 7 deletions

File tree

express-zod-api/src/common-helpers.ts

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -66,12 +66,7 @@ export const ensureError = (subject: unknown): Error =>
6666
subject instanceof Error
6767
? subject
6868
: subject instanceof z.ZodError
69-
? /**
70-
* its message is a serialization of issues, so that I'm making it readable here
71-
* @todo rm if fixed:
72-
* @link https://github.com/colinhacks/zod/pull/4436/
73-
* */
74-
new Error(getMessageFromError(subject), { cause: subject })
69+
? new z.ZodRealError(subject.issues) // ZodError is not an instance of Error, unlike ZodRealError that is
7570
: new Error(String(subject));
7671

7772
export const getMessageFromError = (error: Error): string => {

express-zod-api/tests/common-helpers.spec.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,15 @@ describe("Common Helpers", () => {
225225
message: "invalid type",
226226
},
227227
]),
228-
"invalid type",
228+
"[\n" +
229+
" {\n" +
230+
' "code": "invalid_type",\n' +
231+
' "expected": "string",\n' +
232+
' "input": 123,\n' +
233+
' "path": [],\n' +
234+
' "message": "invalid type"\n' +
235+
" }\n" +
236+
"]",
229237
],
230238
[createHttpError(500, "Internal Server Error"), "Internal Server Error"],
231239
[undefined, "undefined"],

express-zod-api/tests/env.spec.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,23 @@ describe("Environment checks", () => {
6161
Object.getOwnPropertyDescriptors(schema._zod.def.shape),
6262
).toMatchSnapshot();
6363
});
64+
65+
test("ZodError inequality", () => {
66+
const issue: z.core.$ZodIssue = {
67+
code: "invalid_type",
68+
expected: "string",
69+
input: 123,
70+
path: [],
71+
message: "expected string, received number",
72+
};
73+
const error = new z.ZodError([issue]);
74+
const real = new z.ZodRealError([issue]);
75+
expect(error).not.toBeInstanceOf(Error); // and this is important
76+
expect(real).toBeInstanceOf(Error);
77+
expect(real).toBeInstanceOf(z.ZodError); // important inheritance
78+
expect(error).toHaveProperty("message");
79+
expect(real).toHaveProperty("message");
80+
});
6481
});
6582

6683
describe("Zod new features", () => {

0 commit comments

Comments
 (0)