Skip to content

Commit fbe8ad1

Browse files
authored
fix(v4): allow dynamic .catch() under unrepresentable: "any" (#5273) (#5925)
`catchProcessor` evaluates `def.catchValue(undefined)` to derive a static `default`. When the callback inspects its `ctx` argument it throws, and `z.toJSONSchema()` surfaced that as a hard error even when the caller opted into lossy conversion. Gate the rethrow on `unrepresentable === "throw"`. Under `"any"`, skip the `default` and fall through with the inner schema (already populated by the preceding `process(def.innerType)` call) — same passthrough shape `pipe(transform, ...)` produces today. Default behaviour is unchanged. Adds a snapshot test for the new path.
1 parent 1fb56a5 commit fbe8ad1

2 files changed

Lines changed: 10 additions & 1 deletion

File tree

packages/zod/src/v4/classic/tests/to-json-schema.test.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,12 @@ describe("toJSONSchema", () => {
325325
// Dynamic catch values
326326
const dynamicCatchSchema = z.string().catch((ctx) => `${ctx.issues.length}`);
327327
expect(() => z.toJSONSchema(dynamicCatchSchema)).toThrow("Dynamic catch values are not supported in JSON Schema");
328+
expect(z.toJSONSchema(dynamicCatchSchema, { unrepresentable: "any" })).toMatchInlineSnapshot(`
329+
{
330+
"$schema": "https://json-schema.org/draft/2020-12/schema",
331+
"type": "string",
332+
}
333+
`);
328334
});
329335

330336
test("string formats", () => {

packages/zod/src/v4/core/json-schema-processors.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -518,7 +518,10 @@ export const catchProcessor: Processor<schemas.$ZodCatch> = (schema, ctx, json,
518518
try {
519519
catchValue = def.catchValue(undefined as any);
520520
} catch {
521-
throw new Error("Dynamic catch values are not supported in JSON Schema");
521+
if (ctx.unrepresentable === "throw") {
522+
throw new Error("Dynamic catch values are not supported in JSON Schema");
523+
}
524+
return;
522525
}
523526
json.default = catchValue;
524527
};

0 commit comments

Comments
 (0)