mirror of
https://github.com/monkeytypegame/monkeytype.git
synced 2025-09-11 17:16:40 +08:00
refactor: better detection of ZodError (@fehmer) (#6258)
This commit is contained in:
parent
60f664117f
commit
a2d91f2a73
2 changed files with 16 additions and 6 deletions
|
@ -1,4 +1,5 @@
|
|||
import { z, ZodError, ZodIssue } from "zod";
|
||||
import { z, ZodIssue } from "zod";
|
||||
import { isZodError } from "./zod";
|
||||
|
||||
/**
|
||||
* Parse a JSON string into an object and validate it against a schema
|
||||
|
@ -16,11 +17,8 @@ export function parseWithSchema<T extends z.ZodTypeAny>(
|
|||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return schema.parse(jsonParsed) as z.infer<T>;
|
||||
} catch (error) {
|
||||
// instanceof ZodError is not working from our module
|
||||
if ((error as ZodError)["issues"] !== undefined) {
|
||||
throw new Error(
|
||||
(error as ZodError).issues.map(prettyErrorMessage).join("\n")
|
||||
);
|
||||
if (isZodError(error)) {
|
||||
throw new Error(error.issues.map(prettyErrorMessage).join("\n"));
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
|
|
12
packages/util/src/zod.ts
Normal file
12
packages/util/src/zod.ts
Normal file
|
@ -0,0 +1,12 @@
|
|||
import { ZodError } from "zod";
|
||||
|
||||
//from https://github.com/colinhacks/zod/pull/3819
|
||||
export function isZodError(error: unknown): error is ZodError {
|
||||
if (!(error instanceof Error)) return false;
|
||||
|
||||
if (error instanceof ZodError) return true;
|
||||
if (error.constructor.name === "ZodError") return true;
|
||||
if ("issues" in error && error.issues instanceof Array) return true;
|
||||
|
||||
return false;
|
||||
}
|
Loading…
Add table
Reference in a new issue