Keep an application running with a safe setting when an environment value is invalid.
Configuration parsing
Zod · Module
.catch() supplies a fallback when schema validation fails. The fallback can be a fixed value or a function that is rerun for each failure and receives the caught error context.
Attach catch to a schema to recover from validation failure with a fallback. The fallback may be a fixed value or a function that runs whenever Zod needs to generate one; the function receives the caught error context.
schema.catch(value)
schema.catch((ctx) => value)| Name | Type | Description |
|---|---|---|
catchValue | unknown | (ctx: { error: ZodError }) => unknown | The value or fallback-producing function used when validation fails. |
A schema that returns its normal parsed output for valid input and the catch value for invalid input.
.catch() when invalid input should produce a fallback rather than propagate a validation error..catch() on an existing schema and provide the fallback value as its argument.import { z } from "zod";
const port = z.number().int().min(1).max(65535).catch(3000);
console.log(port.parse(8080)); // 8080
console.log(port.parse("invalid")); // 3000Valid input passes through; invalid input produces the fallback value.
Configuration parsing
User preferences
Data ingestion
.catch() do in Zod?.catch(value) returns the parsed value when validation succeeds and returns the supplied fallback when validation fails. For example, a number schema with .catch(42) yields the input number for valid input and 42 for invalid input.
Follow-up: How can the fallback be generated dynamically? Pass a function to .catch; Zod re-executes it whenever a catch value is needed and provides the caught error context.
.catch() use a function instead of a constant?The fallback can be a value or a function. A function is useful when the fallback must be computed per failure, and it receives context about the caught error.
Follow-up: What should be checked when using .catch() with a codec? Verify whether the operation is decoding or encoding, because catch is applied only forward.
A successful parse is returned unchanged, while a failed parse is replaced by the catch value. Thus, .catch() turns a validation failure into a successful result containing the fallback.
Follow-up: How does this differ from handling a thrown parse error? The catch schema supplies a value during parsing instead of requiring the caller to catch a ZodError.
z.defaultz.prefaultz.safeParsez.codec