At the end of the last lesson, SightingSchema.parse() stopped last spring’s broken entry and named the missing field in a ZodError. That’s a big step up from “undefined” on the year list, but a thrown error still ends the import. One bad entry in an export of eight would throw away seven good sightings, and the club would rather keep those and hear what went wrong with the rest.
In this lesson, you’ll check each entry without stopping the import, read the reasons Zod gives for a rejected entry, and turn them into a report the club can act on. Start with the method that checks an entry and hands you the outcome instead of throwing an error.
Check a Sighting Without Throwing
When .parse() meets bad data, it throws, so the code after it never runs. Zod schemas have a second method, .safeParse(), that runs the same check but doesn’t throw when the data fails it. It returns a result object that says whether the data passed.
Try it on the entry from the last lesson’s check questions, where Grace Liu’s count arrived as the string "3". Replace the contents of sighting.ts in your millbrook-birders folder with this version:
sighting.ts
1import { z } from "zod";
2
3const SightingSchema = z.object({
4 species: z.string(),
5 count: z.number(),
6 site: z.string(),
7 observer: z.string(),
8});
9
10const text = `{"species":"Atlantic Puffin","count":"3",
11 "site":"Gull Point","observer":"Grace Liu"}`;
12const entry: unknown = JSON.parse(text);
13const result = SightingSchema.safeParse(entry);
14
15console.log(result.success);
Line 13 calls .safeParse() where the last lesson called .parse(). Line 15 logs the result’s success property. Run the file:
$ node sighting.ts
false
This time, nothing throws. The program reaches line 15, and success is false, because the count isn’t a number.
A result comes in one of two shapes. When the data passes, success is true, and data holds the checked sighting, the same value .parse() would have returned. When it fails, success is false, and error holds the ZodError that .parse() would have thrown. If that sounds like a discriminated union, it is one: success is the tag, and its literal type, true or false, tells the checker which shape you have.
The checker uses that tag only if you check it first. Suppose you read the count straight away, as you did with the value from .parse(). Add this line to the end of sighting.ts:
console.log(result.data.count);
Check the project: