raise for to large value

This commit is contained in:
Ruidy 2021-02-19 12:37:19 +01:00
parent 19192a3ab6
commit 196895d3db
3 changed files with 19 additions and 3 deletions

View file

@ -2,7 +2,8 @@ import {
assertStrictEquals, assertStrictEquals,
assertThrows, assertThrows,
} from "https://deno.land/std@0.87.0/testing/asserts.ts"; } 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", () => { Deno.test("Hello test", () => {
const actual = sayHello(); const actual = sayHello();
@ -22,3 +23,8 @@ Deno.test("Hello fails for non strictly positive values", () => {
const id = -1; const id = -1;
assertThrows(() => sayHello(id), ValidationError, "Invalid index: -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");
});

View file

@ -1,10 +1,13 @@
export class ValidationError extends Error {} import { ValidationError } from "./validation.ts";
/** /**
* Display the iconic Hello, World * Display the iconic Hello, World
*/ */
export const sayHello = (id?: number) => { export const sayHello = (id?: number) => {
if (id && id < 1) { if (id && idInValidRange(id)) {
throw new ValidationError(`Invalid index: ${id}`); throw new ValidationError(`Invalid index: ${id}`);
} }
return (id === 5) ? "Bonjour le monde" : "Hello, World!"; return (id === 5) ? "Bonjour le monde" : "Hello, World!";
}; };
const idInValidRange = (id: number) => id < 1 || id > 100;

7
src/validation.ts Normal file
View file

@ -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 {}