diff --git a/src/index.test.ts b/src/index.test.ts index 66c6250..5816e06 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -2,7 +2,8 @@ import { assertStrictEquals, assertThrows, } from "https://deno.land/std@0.87.0/testing/asserts.ts"; -import { sayHello, ValidationError } from "./index.ts"; +import { sayHello } from "./index.ts"; +import { ValidationError } from "./validation.ts"; Deno.test("Hello test", () => { const actual = sayHello(); @@ -22,3 +23,8 @@ Deno.test("Hello fails for non strictly positive values", () => { const id = -1; assertThrows(() => sayHello(id), ValidationError, "Invalid index: -1"); }); + +Deno.test("Hello fails for too large values", () => { + const id = 666; + assertThrows(() => sayHello(id), ValidationError, "Invalid index: 666"); +}); diff --git a/src/index.ts b/src/index.ts index 2b1c5a6..9cfe9ce 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,10 +1,13 @@ -export class ValidationError extends Error {} +import { ValidationError } from "./validation.ts"; + /** * Display the iconic Hello, World */ export const sayHello = (id?: number) => { - if (id && id < 1) { + if (id && idInValidRange(id)) { throw new ValidationError(`Invalid index: ${id}`); } return (id === 5) ? "Bonjour le monde" : "Hello, World!"; }; + +const idInValidRange = (id: number) => id < 1 || id > 100; diff --git a/src/validation.ts b/src/validation.ts new file mode 100644 index 0000000..bdbb7a2 --- /dev/null +++ b/src/validation.ts @@ -0,0 +1,7 @@ +/** + * Custom error used to express input validation. + * The message must describe to the external user how to correct its input. + * + @example * `throw new ValidationError("Bad id")` + */ +export class ValidationError extends Error {}