Return data and errors #2322
-
I'm finally getting around to taking Zod for a spin. I'm using My use case: I'm fetching a large amount of data and would like to display it all, even if there are a few errors. I can do this by using things like Ultimately i'd like to be informed if there are any errors so I can do something about them, but I don't want to prevent the user from using the app, as it's very likely they wouldn't notice anyway. If {
data: ParsedData,
error: Errors[]
success: Boolean
} |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments 1 reply
-
Perhaps this would help you: If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏 |
Beta Was this translation helpful? Give feedback.
-
Thank you @JacobWeisenburger, this is exactly what I need! |
Beta Was this translation helpful? Give feedback.
-
Same here. First time using zod and it's weird this isn't native functionality. Here's my workaround: const validateObj = (obj) => {
const parsed = schema.safeParse(obj);
if (parsed.success) {
return parsed.data;
} else {
const fieldErrors = parsed.error.flatten().fieldErrors;
for (const field in fieldErrors) {
delete obj[field];
}
return obj;
}
} |
Beta Was this translation helpful? Give feedback.
-
Coming back here after some time with another scenario where I don't want to throw an error and prefer to show the data I have. I'm working around this like so: const data = await res.json();
const parsedResponse = Schema.safeParse(data);
if (!parsedResponse.success) {
console.error(parsedResponse.error);
return data as z.infer<typeof Schema>;
} else {
return parsedResponse.data;
} Not horrific but doesn't feel great either. https://github.com/JacobWeisenburger/zod_utilz#partialsafeparse would be great, however it's doesn't work in the browser nor does it seem to be actively maintained. Is this something that could be considered for the core library? I'd be happy to contribute if so (cc @colinhacks)? |
Beta Was this translation helpful? Give feedback.
-
+1 for this.... I essentially want to use Zod to check the inputs (api calls) to my application and report errors (to sentry/bugsnag/etc) however I don't want like e.g. one individual field missing somewhere far down a object graph to blow up the entire application when it would really only affect one small isolated part of it |
Beta Was this translation helpful? Give feedback.
-
I have updated |
Beta Was this translation helpful? Give feedback.
I have updated
zod_utilz
to work in the browser. So give this a try: https://github.com/JacobWeisenburger/zod_utilz#partialsafeparse