nicer error handling

This commit is contained in:
Siddharth Singh 2024-09-27 21:29:01 +05:30
parent 8511ae2137
commit 4a432e6a23
No known key found for this signature in database
2 changed files with 10 additions and 9 deletions

View file

@ -27,5 +27,10 @@ async function main() {
}
if (import.meta.main) {
try {
await main();
} catch (e) {
console.error('ERROR:', e.message);
Deno.exit(1);
}
}

View file

@ -12,26 +12,22 @@ export class Command {
this.description = description;
}
get subcommandCount() {
return Object.keys(this.commands).length;
}
isValidSubcommand(key: string): boolean {
return Object.keys(this.commands).includes(key.toString());
}
getSubcommand(subcommand: string | number) {
if (!subcommand) {
throw new Error('tribes-cli: error: invalid subcommand');
throw new Error('tribes-cli: invalid subcommand');
}
if (typeof subcommand === 'number') {
throw new Error('tribes-cli: error: subcommand cannot be a number');
throw new Error('tribes-cli: subcommand cannot be a number');
}
if (this.isValidSubcommand(subcommand)) {
return this.commands[subcommand];
} else {
throw new Error(`tribes-cli: error: ${subcommand} is not a valid subcommand`);
throw new Error(`tribes-cli: ${subcommand} is not a valid subcommand`);
}
}
@ -42,7 +38,7 @@ export class Command {
subcommand(name: string, command: Command) {
if (this.isValidSubcommand(name)) {
throw new Error(`tribes-cli: error: ${name} is already a subcommand.`);
throw new Error(`tribes-cli: ${name} is already a subcommand.`);
}
this.commands[name] = command;
return this;