Skip to content

Commit

Permalink
fix(flags): print formatted error message for boolean and number vali…
Browse files Browse the repository at this point in the history
…dation errors (#189)
  • Loading branch information
c4spar committed Apr 24, 2021
1 parent 3dd6315 commit 2a19c34
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 16 deletions.
16 changes: 15 additions & 1 deletion flags/_errors.ts
@@ -1,5 +1,5 @@
import { didYouMeanOption, didYouMeanType, getFlag } from "./_utils.ts";
import type { IFlagOptions } from "./types.ts";
import type { IFlagOptions, ITypeInfo } from "./types.ts";

export class FlagsError extends Error {
constructor(message: string) {
Expand Down Expand Up @@ -148,3 +148,17 @@ export class NoArguments extends ValidationError {
Object.setPrototypeOf(this, NoArguments.prototype);
}
}

export class InvalidTypeError extends ValidationError {
constructor(
{ label, name, value, type }: ITypeInfo,
expected?: Array<string>,
) {
super(
`${label} "${name}" must be of type "${type}", but got "${value}".` + (
expected ? ` Expected values: ${expected.join(", ")}` : ""
),
);
Object.setPrototypeOf(this, MissingOptionValue.prototype);
}
}
11 changes: 5 additions & 6 deletions flags/types/boolean.ts
@@ -1,18 +1,17 @@
import type { ITypeHandler, ITypeInfo } from "../types.ts";
import { InvalidTypeError } from "../_errors.ts";

/** Boolean type handler. Excepts `true`, `false`, `1`, `0` */
export const boolean: ITypeHandler<boolean> = (
{ label, name, value, type }: ITypeInfo,
type: ITypeInfo,
): boolean => {
if (~["1", "true"].indexOf(value)) {
if (~["1", "true"].indexOf(type.value)) {
return true;
}

if (~["0", "false"].indexOf(value)) {
if (~["0", "false"].indexOf(type.value)) {
return false;
}

throw new Error(
`${label} "${name}" must be of type "${type}", but got "${value}".`,
);
throw new InvalidTypeError(type);
};
13 changes: 5 additions & 8 deletions flags/types/number.ts
@@ -1,14 +1,11 @@
import type { ITypeHandler, ITypeInfo } from "../types.ts";
import { InvalidTypeError } from "../_errors.ts";

/** Number type handler. Excepts any numeric value. */
export const number: ITypeHandler<number> = (
{ label, name, value, type }: ITypeInfo,
): number => {
if (isNaN(Number(value))) {
throw new Error(
`${label} "${name}" must be of type "${type}", but got "${value}".`,
);
export const number: ITypeHandler<number> = (type: ITypeInfo): number => {
if (!isNaN(Number(type.value))) {
return parseFloat(type.value);
}

return parseFloat(value);
throw new InvalidTypeError(type);
};
1 change: 0 additions & 1 deletion pagic.config.tsx
@@ -1,4 +1,3 @@
// deno-lint-ignore no-unused-vars
import { React } from "https://deno.land/x/pagic/mod.ts";

export default {
Expand Down

0 comments on commit 2a19c34

Please sign in to comment.