CLI Error Handler

6.2.0 · active · verified Wed Apr 22

handle-cli-error is a robust error handling library specifically designed for Node.js command-line interface (CLI) applications. It provides a comprehensive solution for displaying errors to users in a clear, consistent, and visually appealing manner, then gracefully exiting the process. The current stable version is 6.2.0, with frequent minor releases introducing new features and improvements, such as enhanced customization options. Key differentiators include its ability to generate pretty, colorized error output with icons and headers, support for error class-specific handling (allowing different exit codes or logging behaviors per error type), graceful process exit with customizable timeouts, and automatic normalization of invalid Error objects using `normalize-exception`. It also allows fine-grained control over what error details are logged, such as stack traces, nested error causes, and additional error properties, making it highly configurable for various CLI needs.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic usage of `handleCliError` within a try-catch block, including error class-specific options and custom configuration for output.

import handleCliError from 'handle-cli-error';

const main = async () => {
  try {
    // Simulate a CLI operation that might fail
    const result = await Promise.resolve('some_data');
    if (result !== 'expected_data') {
      throw new Error('Unexpected data received. This is a critical error.', { cause: 'Data mismatch' });
    }
    console.log('CLI operation successful!');
  } catch (error) {
    handleCliError(error, {
      classes: {
        TypeError: { exitCode: 1, stack: false, props: false },
        Error: { exitCode: 2, cause: true },
        default: { exitCode: 3, colors: true, silent: process.env.NODE_ENV === 'test' },
      },
      header: 'CLI Error: {name}', // Custom header format
      exitCode: 99, // Fallback exit code
    });
  }
};

main();

view raw JSON →