Skip to content

Commit 287b126

Browse files
committed
Improve handling of ZodError by ensureError.
1 parent 83dfadd commit 287b126

3 files changed

Lines changed: 14 additions & 23 deletions

File tree

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ export const ensureError = (subject: unknown): Error =>
6767
subject instanceof Error
6868
? subject
6969
: subject instanceof z.ZodError
70-
? new Error(subject.message)
70+
? new Error(getMessageFromError(subject), { cause: subject })
7171
: new Error(String(subject));
7272

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

express-zod-api/tests/__snapshots__/system.spec.ts.snap

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -122,24 +122,17 @@ exports[`App in production mode > Validation > Problem 787: Should NOT treat Zod
122122
"Server side error",
123123
{
124124
"error": InternalServerError({
125-
"cause": Error({
126-
"message": "[
127-
{
128-
"expected": "number",
129-
"code": "invalid_type",
130-
"path": [],
131-
"message": "Invalid input: expected number, received string"
132-
}
133-
]",
134-
}),
135-
"message": "[
136-
{
137-
"expected": "number",
138-
"code": "invalid_type",
139-
"path": [],
140-
"message": "Invalid input: expected number, received string"
141-
}
142-
]",
125+
"cause": ZodError {
126+
"issues": [
127+
{
128+
"code": "invalid_type",
129+
"expected": "number",
130+
"message": "Invalid input: expected number, received string",
131+
"path": [],
132+
},
133+
],
134+
},
135+
"message": "Invalid input: expected number, received string",
143136
}),
144137
"payload": {
145138
"key": "123",

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

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -349,13 +349,11 @@ describe("Common Helpers", () => {
349349
code: "invalid_type",
350350
expected: "string",
351351
input: 123,
352-
path: [""],
352+
path: [],
353353
message: "invalid type",
354354
},
355355
]),
356-
`[\n {\n "code": "invalid_type",\n "expected": "string",\n` +
357-
` "input": 123,\n "path": [\n ""\n` +
358-
` ],\n "message": "invalid type"\n }\n]`,
356+
"invalid type",
359357
],
360358
[createHttpError(500, "Internal Server Error"), "Internal Server Error"],
361359
[undefined, "undefined"],

0 commit comments

Comments
 (0)