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

Feature Request: Pass more data to catch to simplify error reporting and fallbacks #1732

Closed
edzis opened this issue Dec 20, 2022 · 1 comment
Labels
enhancement New feature or request

Comments

@edzis
Copy link

edzis commented Dec 20, 2022

Level 1 - pass error and input

export const schemaWithErrorCapture = <
  O,
  D extends ZodTypeDef,
  S extends Schema<O, D, unknown>,
>(
  schema: S,
): ZodCatch<ZodNullable<S>> => {
  return schema.nullable().catch((cause, input) => {
    captureException(
      new Error(`parse failed for ${schema.description || 'UnnamedSchema'}`, {
        cause,
      }),
      { extra: { dataRaw } },
    );
    return null;
  });
};

const dataOrNull = schemaWithErrorCapture($Response).parse(dataRaw);

Level 2 - enable transformations in catch - avoids nullable in my case:

export const schemaWithErrorCapture = <
  O,
  D extends ZodTypeDef,
  S extends Schema<O, D, unknown>,
>(
  schema: S,
): ZodCatch<S, null> => {
  return schema.catch((cause, input) => {
    captureException(
      new Error(`parse failed for ${schema.description || 'UnnamedSchema'}`, {
        cause,
      }),
      { extra: { dataRaw } },
    );
    return null;
  });
};

const dataOrNull = schemaWithErrorCapture($Response).parse(dataRaw);

Level 3 - pass also the schema - enables a generic function to be used in catch:

const handleParseError = (
  error: ZodError,
  input: unknown,
  schema: Schema,
): null => {
  captureException(
    new Error(
      `parse failed for ${schema.description || 'UnnamedSchema'}`,
      { cause: error },
    ),
    { extra: { input } },
  );
  return null;
};

const dataOrNull = $Response.catch(handleParseError).parse(dataRaw);

What I have currently - safeParse:

const parseSchemaHard = <
  O,
  D extends ZodTypeDef,
  S extends Schema<O, D, unknown>,
>(
  schema: S,
  dataRaw: unknown,
): z.infer<S> | null => {
  const result = schema.safeParse(dataRaw);

  if (!result.success) {
    captureException(
      new Error(`parse failed for ${schema.description || 'UnnamedSchema'}`, {
        cause: result.error,
      }),
      { extra: { dataRaw } },
    );
    return null;
  }
  return result.data;
};

const dataOrNull = parseSchemaHard($Response, dataRaw);
@JacobWeisenburger JacobWeisenburger added the enhancement New feature or request label Dec 24, 2022
@edzis
Copy link
Author

edzis commented Apr 2, 2023

I noticed today that the critical pieces are covered in #2087 by @0xWryth and in ac0135e by @colinhacks.

  catch(
    def: (ctx: { error: ZodError; input: Input }) => Output
  ): ZodCatch<this>;`

On top of that I now realize that:

  • we can get the schema using this
  • and allowing a different return type in catch (as in transform) might not be desired.

Based on this I believe that this feature request is covered.


In case it helps others, here is my updated approach.

class SchemaError extends UIError {
  constructor(
    action: string,
    schema: Schema,
    dataRaw: unknown,
    cause: ZodError,
  ) {
    const badPaths = map(cause.issues, (issue) => issue.path.join('.'))
      .sort()
      .join(', ');
    const msgBase = `${action} failed for ${
      schema.description || 'unnamed schema'
    }`;
    const message = badPaths ? `${msgBase} - ${badPaths}` : msgBase;

    super(message, {
      sendOnce: true,
      cause,
      sentryContext: {
        extra: {
          dataRaw,
        },
      },
    });
    Object.defineProperty(this, 'name', { value: 'SchemaError' });
  }
}
/* ---------------------------------- CATCH --------------------------------- */
const zCatchThrow = <
  D extends ZodTypeDef,
  S extends Schema<unknown, D, unknown>,
>() =>
  function (this: S, ctx: { input: unknown; error: ZodError }) {
    throw new SchemaError('parseSchema', this, ctx.input, ctx.error);
  };

const zCatchFallback = <
  D extends ZodTypeDef,
  S extends Schema<unknown, D, unknown>,
  F,
>(
  fallback: F,
) =>
  function (this: S, ctx: { input: unknown; error: ZodError }): F {
    captureException(
      new SchemaError('parseSchemaWithFallback', this, ctx.input, ctx.error),
    );
    return fallback;
  };
/* ----------------------------------- OR ----------------------------------- */
export const zOrThrow = <
  D extends ZodTypeDef,
  S extends Schema<unknown, D, unknown>,
>(
  schema: S,
) => {
  return schema.catch(zCatchThrow());
};

export const zOrNull = <
  D extends ZodTypeDef,
  S extends Schema<unknown, D, unknown>,
>(
  schema: S,
) => {
  return schema.catch(zCatchFallback(null)) as unknown as ZodCatch<
    ZodNullable<S>
  >;
};

export const zOrUndefined = <
  D extends ZodTypeDef,
  S extends Schema<unknown, D, unknown>,
>(
  schema: S,
) => {
  return schema.catch(zCatchFallback(undefined)) as unknown as ZodCatch<
    ZodOptional<S>
  >;
};

export const zOrFallback = <
  D extends ZodTypeDef,
  S extends Schema<unknown, D, unknown>,
  F extends z.TypeOf<S>,
>(
  schema: S,
  fallback: F,
) => {
  return schema.catch(zCatchFallback(fallback));
};
export const getA = (dataRaw: unknown) => zOrThrow(MySchema).parse(dataRaw);
export const getA = (dataRaw: unknown) => zOrNull(MySchema).parse(dataRaw);
export const getA = (dataRaw: unknown) => zOrUndefined(MySchema).parse(dataRaw);
export const getA = (dataRaw: unknown) => zOrFallback(MySchema, 'legalValue').parse(dataRaw);

@edzis edzis closed this as completed Apr 2, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants