Create an error from multiple errors
94
Build a validation system that collects and categorizes multiple validation errors in a type-safe manner.
Create a validation system with the following features:
Define custom error types for different validation scenarios:
ValidationError class that extends Error with a field property (string) and a code property (string)RangeError class that extends Error with min and max properties (numbers)Implement a validateUser function that:
name (string), email (string), age (number)name is not empty (error code: 'NAME_REQUIRED')email contains an '@' symbol (error code: 'EMAIL_INVALID')age is between 0 and 120 (use RangeError with min: 0, max: 120)Implement a handleValidationErrors function that:
When a user object has an empty name, missing '@' in email, and age of -5, the validator should collect all three errors (name validation error, email validation error, and range error) and the error handler should aggregate them into a single error that maintains type information for each individual error. @test
When a user object is valid (name: "John", email: "john@example.com", age: 25), the validator should return an empty array and the error handler should return null. @test
@generates
export class ValidationError extends Error {
field: string;
code: string;
constructor(message: string, field: string, code: string);
}
export class RangeError extends Error {
min: number;
max: number;
constructor(message: string, min: number, max: number);
}
export interface User {
name: string;
email: string;
age: number;
}
export function validateUser(user: User): Array<ValidationError | RangeError>;
export function handleValidationErrors(errors: Array<ValidationError | RangeError>): Error | null;Provides error aggregation support for collecting multiple errors into a single error instance.
Install with Tessl CLI
npx tessl i tessl/npm-aggregate-errordocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9