Catch / Fallback
▶ Open in PlaygroundEvery schema builder supports .catch(value). When validation fails for any reason — wrong type, constraint violation, missing required value — the fallback is returned as a successful result instead of errors.
Unlike .default(), which only fires when the input is undefined, .catch() fires on any validation failure. When .catch() is set, .validate() and .validateAsync() will never throw.
import { string, number, array } from '@cleverbrush/schema';
// Static fallback
const Name = string().catch('unknown');
Name.validate(42); // { valid: true, object: 'unknown' }
Name.validate(null); // { valid: true, object: 'unknown' }
Name.validate('Alice'); // { valid: true, object: 'Alice' }
// Constraint violation also triggers catch
const Age = number().min(0).catch(-1);
Age.validate(-5); // { valid: true, object: -1 }
// .validate() never throws when .catch() is set
Name.validate(42); // { valid: true, object: 'unknown' }
Use a factory function for mutable fallback values to avoid shared references between calls:
const Tags = array(string()).catch(() => []);
const r1 = Tags.validate(null); // { valid: true, object: [] }
const r2 = Tags.validate(null); // { valid: true, object: [] }
// r1.object !== r2.object — a fresh [] each time
// Introspect the fallback state
const schema = string().catch('unknown');
const info = schema.introspect();
console.log(info.hasCatch); // true
console.log(info.catchValue); // 'unknown'