Skip to content

Commit

Permalink
refactor: improving handleError utility method
Browse files Browse the repository at this point in the history
  • Loading branch information
thetutlage committed Oct 16, 2019
1 parent 57b6acb commit 067c240
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 10 deletions.
40 changes: 30 additions & 10 deletions src/utils/handleError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,45 @@
* file that was distributed with this source code.
*/

import { red, bgRed } from 'kleur'
import { Colors } from '@poppinss/colors'
import logger from '@poppinss/fancy-logs'
import { CommandConstructorContract } from '../Contracts'
import { InvalidFlagType } from '../Exceptions/InvalidFlagType'
import { MissingCommandArgument } from '../Exceptions/MissingCommandArgument'

const colors = new Colors()

/**
* Prints additional help for a given command
*/
function printAdditionalHelp (command?: CommandConstructorContract) {
if (!command) {
return
}

const commandHelp = colors.yellow(`adonis ${command.commandName} --help`)
const message = `Consult the command help by typing ${commandHelp}`
console.log(` ${message}`)
}

/**
* Handles the command errors and prints them to the console.
*/
export function handleError (error: any) {
if (error.name === 'CommandValidationException') {
console.log(red(error.message))
console.log(bgRed('This is a programming error. Make sure to read the docs'))
if (error instanceof MissingCommandArgument) {
const { command, argumentName } = error
logger.error(`Missing argument {${argumentName}}`)
printAdditionalHelp(command)
return
}

if (error.name === 'InvalidArgumentException') {
console.log(bgRed('Error'))
console.log(red(error.message))
if (error instanceof InvalidFlagType) {
const { command, argumentName, exceptedType } = error
const message = `Expected {${argumentName}} to be a valid {${exceptedType}}`
logger.error(message)
printAdditionalHelp(command)
return
}

console.log(bgRed('Fatal error'))
console.log(red(error.message))
console.log(error.stack)
logger.fatal(error)
}
6 changes: 6 additions & 0 deletions src/utils/help.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ function wrapArg (arg: CommandArg): string {
return arg.required ? `<${displayName}>` : `[${displayName}]`
}

/**
* Returns an array of flags for displaying the help screen
*/
function getFlagsForDisplay (flags: CommandFlag[]) {
return flags.map(({ name, type, alias, description }) => {
/**
Expand Down Expand Up @@ -61,6 +64,9 @@ function getFlagsForDisplay (flags: CommandFlag[]) {
})
}

/**
* Returns an array of args for displaying the help screen
*/
function getArgsForDisplay (args: CommandArg[]) {
return args.map(({ name, description }) => {
return {
Expand Down

0 comments on commit 067c240

Please sign in to comment.