Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: .safeParse() should not throw #3756

Open
kirkwaiblinger opened this issue Sep 16, 2024 · 0 comments
Open

Bug: .safeParse() should not throw #3756

kirkwaiblinger opened this issue Sep 16, 2024 · 0 comments

Comments

@kirkwaiblinger
Copy link

kirkwaiblinger commented Sep 16, 2024

From the docs,

If you don't want Zod to throw errors when validation fails, use .safeParse. This method returns an object containing either the successfully parsed data or a ZodError instance containing detailed information about the validation problems.

This works fine and well so long as you stick to built-in refinements and schemas. But, if you make your own transformations/refinements, and they throw, then safeparse will throw.

const throwingSchema = z.any().transform((args, context) => {
   throw new Error('lol');
});

const resultShouldntThrow = throwingSchema.safeParse("please don't throw!");

I understand that user-defined .transform() and .refine() functions are not intended to throw, so they constitute an invalid schema. However, I would expect that to be reported from .safeParse() in a non-throwing way, for example

throwingSchema.safeParse("please don't throw!"); // { valid: false, code: 'INVALID_SCHEMA', message: 'Exception was thrown during user-defined `.transform()` callback' }

If we really want a method called "safeX" to throw, I would expect it to come in the form of an opt-in option, such as

throwingSchema.safeParse("please don't throw!", { throwOnInvalidSchema: true }); // Uncaught: ZodErrorInvalidSchema

Otherwise, we're stuck with

let parseResult;
try {
   parseResult = throwingSchema.safeParse("please don't throw!");
} catch (error) {
   // handle secondary error path
}
if (!parseResult.valid) {
   // handle primary error path
}

which defeats the purpose of safeParse in the first place.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant