Skip to content

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

@justinmchase

Description

@justinmchase
  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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions