Custom InputError for user input in TypeScript
8 An InputError for user input
easyWrite a custom error for invalid input and use it to validate what a user submitted, showing a helpful message for each problem.
Stuck? Three hints, smallest first
- 1. Collect every problem before reporting, rather than stopping at the first one.
- 2. A form that reports one error at a time is a bad form.
- 3. Carry the list of problems on the error so the caller can render them all.
const same = (a: unknown, b: unknown): boolean =>
JSON.stringify(a) === JSON.stringify(b);
function test(name: string, got: unknown, want: unknown): void {
console.log(
(same(got, want) ? 'ok ' : 'FAIL ') + name +
(same(got, want) ? '' : ` got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
);
}
class InputError extends Error {
constructor(public readonly problems: string[]) {
super(`${problems.length} problem(s) with the input`);
this.name = 'InputError';
}
}
interface Form {
name?: string;
email?: string;
seats?: number;
}
function validate(form: Form): { name: string; email: string; seats: number } {
const problems: string[] = [];
if (typeof form.name !== 'string' || form.name.trim().length < 2) {
problems.push('name must be at least 2 characters');
}
if (typeof form.email !== 'string' || !form.email.includes('@')) {
problems.push('email must contain @');
}
if (typeof form.seats !== 'number' || !Number.isInteger(form.seats) || form.seats < 1) {
problems.push('seats must be a whole number of 1 or more');
}
// Report everything at once, not just the first fault.
if (problems.length > 0) throw new InputError(problems);
return { name: form.name!.trim(), email: form.email!, seats: form.seats! };
}
function submit(form: Form): string {
try {
const clean = validate(form);
return `booked ${clean.seats} for ${clean.name}`;
} catch (err) {
if (err instanceof InputError) return `rejected:\n - ${err.problems.join('\n - ')}`;
throw err;
}
}
console.log(submit({ name: 'Amaka Obi', email: 'amaka@example.com', seats: 2 }));
console.log(submit({ name: 'A', email: 'nope', seats: 0 }));
const threeProblems = (() => {
try { validate({}); return 0; }
catch (err) { return err instanceof InputError ? err.problems.length : 0; }
})();
test('a good form', submit({ name: 'Amaka Obi', email: 'amaka@example.com', seats: 2 }), 'booked 2 for Amaka Obi');
test('an empty form reports all three faults', threeProblems, 3);
test('the name is trimmed', validate({ name: ' Bola ', email: 'b@x.com', seats: 1 }).name, 'Bola');
test('one bad field is reported alone', (() => { try { validate({ name: 'Amaka', email: 'x@y.com', seats: 0 }); return 0; } catch (e) { return e instanceof InputError ? e.problems.length : 0; } })(), 1);
Output
The design choice here matters more than the class. Collecting all the problems and throwing once means the user fixes their form in one pass. Throwing on the first fault makes them submit, fix, submit, fix. The error carries problems as an array precisely so the caller can render the whole list.