Implement user-friendly CLI error handling
✓Works with OpenClaudeYou are a Node.js CLI developer. The user wants to implement user-friendly CLI error handling that catches errors, formats them clearly, and provides actionable guidance to users.
What to check first
- Verify your CLI entry point uses
#!/usr/bin/env nodeshebang and has proper error boundaries - Check if you're using a CLI framework like
commander,yargs,oclif, or plain Node.jsprocessAPIs - Run
npm list chalk orato see if you have color and spinner libraries for enhanced output
Steps
- Create an error handler wrapper function that catches synchronous and asynchronous errors
- Define custom error classes for different error types (validation, file system, API, etc.)
- Add a global
process.on('uncaughtException')listener to catch unhandled synchronous errors - Add a global
process.on('unhandledRejection')listener to catch unhandled promise rejections - Implement a
formatError()function that outputs colored, structured error messages with context - Add a
--verboseor--debugflag to your CLI to conditionally show stack traces - Use
process.exit()with appropriate exit codes (1 for general errors, specific codes for different failure types) - Test error handling by deliberately triggering different error scenarios
Code
#!/usr/bin/env node
const chalk = require('chalk');
const path = require('path');
// Custom error classes
class CLIError extends Error {
constructor(message, exitCode = 1, details = null) {
super(message);
this.name = 'CLIError';
this.exitCode = exitCode;
this.details = details;
}
}
class ValidationError extends CLIError {
constructor(message, details = null) {
super(message, 2, details);
this.name = 'ValidationError';
}
}
class FileNotFoundError extends CLIError {
constructor(filePath) {
super(`File not found: ${filePath}`, 3, { filePath });
this.name = 'FileNotFoundError';
}
}
// Error formatter
function formatError(error, verbose = false) {
const separator = chalk.gray('─'.repeat(60));
let output = `\n${separator}\n`;
if (error instanceof CLIError) {
output += chalk.red.bold(`✖ ${error.name}\n`);
output += chalk.white(error.message);
if (error.details) {
output += chalk.gray(`\n\nDetails:\n`);
output += chalk.gray(JSON.stringify(error.details, null, 2));
}
} else {
output += chalk.red.bold(`✖ Unexpected Error\n`);
output += chalk.white(error.message || 'Unknown error occurred');
}
if (verbose &&
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related CLI Tools Skills
Other Claude Code skills in the same category — free to download.
CLI App Builder
Build CLI applications with Commander.js
Interactive CLI
Create interactive CLI prompts (Inquirer.js)
CLI Progress Bar
Add progress bars and spinners to CLI
CLI Config Manager
Build CLI configuration management
CLI Help Generator
Generate help text and man pages
CLI Testing
Test CLI applications
CLI Packaging
Package CLI for npm/brew distribution
CLI Autocomplete
Add shell autocompletion to CLI tools
Want a CLI Tools skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.