Skip to content

Class: CommandError ​

Error for a failure that a command expects, such as a project that does not exist.

When a command throws it from run, or a plugin throws it from a command decorator, the global options plugin prints its message to stderr, followed by a Caused by: line for each cause, without a stack trace. It sets the exit code of the process to CommandError.exitCode, and cli() resolves with undefined. onErrorCommand is still called with the error, after the exit code is set, so the hook can change it.

It is not printed, and cli() rejects with it, in these cases:

  • usageSilent is set, for the caller to report it
  • it is thrown from a hook, while a plugin extends the command context, or while a lazy command loads, outside the command decorators
  • the CLI runs without the global options plugin, as gunshi/bone does

Any other error thrown from a command is not printed either, and cli() rejects with it.

Each package of gunshi (gunshi, @gunshi/plugin, @gunshi/definition) bundles its own copy of this class, so instanceof does not match an error from another copy. Use isCommandError to tell it.

Extends ​

  • Error

Signature ​

ts
export class CommandError extends Error

Constructors ​

Constructor ​

ts
new CommandError(message: string, options: CommandErrorOptions = {}): CommandError;

Create an error for a failure that a command expects.

Parameters ​

NameTypeDescription
messagestringThe message printed to the user. It may have more than one line.
optionsCommandErrorOptionsThe code, the exit code and the cause of the failure (optional, default: {})

Returns ​

CommandError

Properties ​

NameTypeDescription
code (optional, readonly)stringThe name of the failure, for programs to read. See CommandErrorOptions.code.
exitCode (readonly)numberThe exit code of the process, an integer from 1 to 255.

Examples ​

js
import { CommandError, define } from 'gunshi'

export default define({
  name: 'show',
  args: { project: { type: 'positional', description: 'Project name' } },
  run: async ctx => {
    const project = await findProject(ctx.values.project)
    if (!project) {
      throw new CommandError(`Project ${ctx.values.project} not found`, { code: 'not_found' })
    }
    ctx.log(project.description)
  }
})

Released under the MIT License.