zod
zod copied to clipboard
Introduce ZodTransformError type, to allow for transforms that fail
This PR introduces a new Error type, ZodTransformError, which accepts an array of issues in it's constructor.
Closes https://github.com/colinhacks/zod/issues/1390
When thrown inside a transform, this error class will be caught by Zod, and the issues it contains treated a fatal and added to the parse result.
The rational for this PR is to allow for transforms that may fail, such as the following example.
import { ZodTransformError } from "zod";
const user = z.string().transform(async (id) => {
try {
const user = await getUserById(id);
return user;
} catch (e) {
throw new ZodTransformError([{
code: "custom",
message: "User not found",
}]);
}
});
Deploy Preview for guileless-rolypoly-866f8a ready!
Built without sensitive environment variables
| Name | Link |
|---|---|
| Latest commit | 94c71b53f709a2e9c7138fb2412347bf62bc7cc0 |
| Latest deploy log | https://app.netlify.com/sites/guileless-rolypoly-866f8a/deploys/6318df910e7060000812becb |
| Deploy Preview | https://deploy-preview-1389--guileless-rolypoly-866f8a.netlify.app |
| Preview on mobile | Toggle QR Code...Use your smartphone camera to open QR code link. |
To edit notification comments on pull requests, go to your Netlify site settings.
Deploy Preview for guileless-rolypoly-866f8a ready!
Built without sensitive environment variables
| Name | Link |
|---|---|
| Latest commit | 7db2ad46ff40d8548a1f501c521f12e16149159c |
| Latest deploy log | https://app.netlify.com/sites/guileless-rolypoly-866f8a/deploys/6325cff7e7a39a0009070c6d |
| Deploy Preview | https://deploy-preview-1389--guileless-rolypoly-866f8a.netlify.app |
| Preview on mobile | Toggle QR Code...Use your smartphone camera to open QR code link. |
To edit notification comments on pull requests, go to your Netlify site settings.
@Duncan3142 Would you have visibility for the merge of this new feature or otherwise an alternative use with what is currently in ZOD?
Thanks for this PR! This same scenario can now be addressed with ctx.addIssue inside the .transform() method:
const user = z.string().transform(async (id, ctx) => {
try {
await "asdf";
throw new Error();
} catch (e) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "User not found :(",
});
}
});
Closing for now, let me know if the new solution doesn't cover your use cases.