parse vs safeParse
Handle validation success and failure gracefully.
Two Ways to Validate
Zod gives you two validation methods: parse, which throws on invalid data, and safeParse, which returns a result object instead.
import { z } from "zod";
const schema = z.string();
// schema.parse(x) throws on failure
// schema.safeParse(x) returns { success, ... }parse Throws on Invalid Data
parse returns the validated value on success and throws a ZodError on failure, ideal when invalid data is truly exceptional.
import { z } from "zod";
const schema = z.number();
const ok = schema.parse(42); // 42
// schema.parse("nope"); // throws ZodError