- Add
ValidationError class
- Add
formatError function which would format the error into a human readable string
- 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.
ValidationErrorclassformatErrorfunction which would format the error into a human readable string{ expected: 'int32', actual 'string' }or{ expected: 'found', actual: 'missing' }, or whatever is needed to give a readable explanation to a user.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 actualValidationErrorshould look similar to the above.