Skip to content

Commit a2d91f2

Browse files
authored
refactor: better detection of ZodError (@fehmer) (monkeytypegame#6258)
1 parent 60f6641 commit a2d91f2

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed

packages/util/src/json.ts

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import { z, ZodError, ZodIssue } from "zod";
1+
import { z, ZodIssue } from "zod";
2+
import { isZodError } from "./zod";
23

34
/**
45
* Parse a JSON string into an object and validate it against a schema
@@ -16,11 +17,8 @@ export function parseWithSchema<T extends z.ZodTypeAny>(
1617
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
1718
return schema.parse(jsonParsed) as z.infer<T>;
1819
} catch (error) {
19-
// instanceof ZodError is not working from our module
20-
if ((error as ZodError)["issues"] !== undefined) {
21-
throw new Error(
22-
(error as ZodError).issues.map(prettyErrorMessage).join("\n")
23-
);
20+
if (isZodError(error)) {
21+
throw new Error(error.issues.map(prettyErrorMessage).join("\n"));
2422
} else {
2523
throw error;
2624
}

packages/util/src/zod.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { ZodError } from "zod";
2+
3+
//from https://github.com/colinhacks/zod/pull/3819
4+
export function isZodError(error: unknown): error is ZodError {
5+
if (!(error instanceof Error)) return false;
6+
7+
if (error instanceof ZodError) return true;
8+
if (error.constructor.name === "ZodError") return true;
9+
if ("issues" in error && error.issues instanceof Array) return true;
10+
11+
return false;
12+
}

0 commit comments

Comments
 (0)