All files / src/lib form-utils.ts

92.3% Statements 12/13
50% Branches 1/2
100% Functions 3/3
92.3% Lines 12/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51                      10x 174x 7x 7x 5x   2x     2x 2x   2x 13x 13x           2x                                      
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
 
/**
 * Creates a safer Zod resolver that catches and handles validation errors gracefully.
 * This is useful for form validations to prevent unhandled exceptions and provide
 * better error reporting.
 *
 * @param schema - The Zod schema to use for validation
 * @returns A resolver function compatible with react-hook-form
 */
export const createSafeZodResolver = (schema: z.ZodSchema) => {
  return async (values: any, context: any, options: any) => {
    try {
      const result = await zodResolver(schema)(values, context, options);
      return result;
    } catch (error) {
      console.warn('Zod validation error caught:', error);
 
      // Try to parse the error and create proper field errors
      Eif (error instanceof z.ZodError) {
        const fieldErrors: Record<string, any> = {};
 
        error.issues.forEach(issue => {
          const path = issue.path.join('.');
          fieldErrors[path] = {
            type: 'manual',
            message: issue.message,
          };
        });
 
        return {
          values: {},
          errors: fieldErrors,
        };
      }
 
      // Fallback for other errors
      return {
        values: {},
        errors: {
          root: {
            type: 'manual',
            message: 'Validation failed',
          },
        },
      };
    }
  };
};