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

It would be nice if this package had a throwable ValidationError and error formatter #1

Open
justinmchase opened this issue Apr 15, 2023 · 0 comments

Comments

@justinmchase
Copy link

justinmchase commented Apr 15, 2023

  1. Add ValidationError class
  2. Add formatError function which would format the error into a human readable string
  3. Add some extra metadata to the error about the failure such as { expected: 'int32', actual 'string' } or { expected: 'found', actual: 'missing' }, or whatever is needed to give a readable explanation to a user.
const errors = validate(schema, instance);
if (errors.length) {
  throw new ValidationError("Example", errors);
}
export class ValidationError extends Error {
  constructor(
    public readonly schemaName: string,
    public readonly errors: SchemaValidationError[],
  ) {
    super(`A validation error occurred for type ${this.schemaName}`)
    this.name = "ValidationError";
  }
}
import { ValidationError, formatError } from "jtd/mod.ts";

try {
  example();
} catch (err) {
  if (err instanceof ValidationError) {
    console.log(err.message)
    for (const error of err.errors) {
      console.log(formatError(error));
    }
  }
}

Theoretically I can use the instance path to identify the exact field, so if I was in a UI form I could essentially attach the formatted error onto the form element for display.

You have a bit of a name conflict where your return type from the validate function is ValidationError, which in javascript the word Error is reserved for types which extend the Error class. So seems like that should be renamed to something else and then the actual ValidationError should look similar to the above.

@justinmchase justinmchase changed the title It would be nice if this package had a ValidationError and error formatter It would be nice if this package had a throwable ValidationError and error formatter Apr 15, 2023
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