CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-unocss--cli

CLI for UnoCSS that enables CSS generation from utility classes in traditional backends and static environments.

Pending
Overview
Eval results
Files

errors.mddocs/

Error Handling

Specialized error handling for CLI operations with user-friendly messages and proper exit codes, designed to provide clear feedback for common CLI usage issues.

Capabilities

Pretty Error Class

Custom error class for user-friendly CLI error messages with proper stack trace handling.

/**
 * Custom error class for user-friendly CLI error messages
 * Extends standard Error with proper stack trace capture
 */
class PrettyError extends Error {
  /**
   * Creates a new PrettyError with user-friendly message
   * @param message - Human-readable error message to display
   */
  constructor(message: string);
}

Usage Examples:

// Note: PrettyError may not be directly exported from main package entry
import { PrettyError } from "@unocss/cli";

// Throw user-friendly error
function validateInput(patterns: string[]) {
  if (!patterns || patterns.length === 0) {
    throw new PrettyError(
      "No glob patterns provided, try unocss <path/to/**/*>"
    );
  }
}

// Handle in try-catch
try {
  validateInput([]);
} catch (error) {
  if (error instanceof PrettyError) {
    console.error("Configuration error:", error.message);
  }
}

Global Error Handler

Global error handler for CLI operations that manages process exit codes and user feedback.

/**
 * Global error handler for CLI operations
 * Sets process exit code and logs appropriate error messages
 * @param error - Error to handle (PrettyError or generic error)
 */
function handleError(error: unknown): void;

Usage Examples:

// Note: handleError may not be directly exported from main package entry
import { handleError, build } from "@unocss/cli";

// Handle build errors gracefully
async function runBuild() {
  try {
    await build({
      patterns: ["src/**/*.html"],
      outFile: "dist/styles.css",
    });
  } catch (error) {
    handleError(error);
    // Process will exit with code 1
  }
}

// Use as global handler
process.on('unhandledRejection', handleError);
process.on('uncaughtException', handleError);

Error Types and Scenarios

Configuration Errors

Common configuration-related errors and their messages:

// Missing patterns
throw new PrettyError(
  "No glob patterns, try unocss <path/to/**/*>"
);

// Invalid output configuration (logged as fatal, doesn't throw)
// consola.fatal("Cannot use --stdout and --out-file at the same time")
// Function returns early without throwing

// Configuration file not found
throw new PrettyError(
  "Configuration file not found: uno.config.js"
);

File System Errors

File system related errors are handled gracefully:

// File permission errors
try {
  await fs.writeFile(outFile, css, 'utf-8');
} catch (error) {
  throw new PrettyError(
    `Cannot write to output file: ${outFile}. Check permissions.`
  );
}

// Directory creation errors  
try {
  await fs.mkdir(dir, { recursive: true });
} catch (error) {
  throw new PrettyError(
    `Cannot create output directory: ${dir}`
  );
}

UnoCSS Processing Errors

Errors during CSS generation are wrapped for better user experience:

// Token processing errors
try {
  const { css } = await ctx.uno.generate(tokens);
} catch (error) {
  throw new PrettyError(
    `CSS generation failed: ${error.message}`
  );
}

// Transformer errors
try {
  const result = await applyTransformers(ctx, code, id);
} catch (error) {
  throw new PrettyError(
    `Transformer processing failed for ${id}: ${error.message}`
  );
}

Error Handling Patterns

CLI Error Handling

The CLI startup process includes comprehensive error handling:

import { startCli, handleError } from "@unocss/cli";

// CLI entry point with error handling
startCli().catch(handleError);

Programmatic Error Handling

When using the programmatic API, errors should be handled appropriately:

import { build, PrettyError, handleError } from "@unocss/cli";

async function safeBuild(options: CliOptions) {
  try {
    await build(options);
    console.log("✅ Build completed successfully");
  } catch (error) {
    if (error instanceof PrettyError) {
      // User-friendly error - log and exit gracefully
      console.error("❌ Build failed:", error.message);
      process.exit(1);
    } else {
      // Unexpected error - use global handler
      handleError(error);
    }
  }
}

Watch Mode Error Handling

File watching includes error recovery mechanisms:

// Watcher error handling
watcher.on('error', (error) => {
  console.error('File watcher error:', error.message);
  // Watcher continues running for other files
});

// Configuration reload error handling
try {
  await ctx.reloadConfig();
} catch (error) {
  console.error('Configuration reload failed:', error.message);
  // Falls back to previous configuration
}

Error Recovery

The CLI includes several error recovery mechanisms:

Graceful Degradation

  • Configuration errors: Falls back to default configuration
  • File permission errors: Continues processing other files
  • Transformer errors: Skips problematic transformers
  • Watch errors: Continues monitoring other files

User Guidance

Error messages include actionable guidance:

  • Missing patterns: Suggests correct usage syntax
  • Permission errors: Indicates file permission requirements
  • Configuration errors: Points to configuration file issues
  • Output conflicts: Explains conflicting options

Process Management

  • Exit codes: Sets appropriate exit codes for different error types
  • Signal handling: Gracefully shuts down watchers on process termination
  • Resource cleanup: Ensures file handles and watchers are properly closed

Install with Tessl CLI

npx tessl i tessl/npm-unocss--cli

docs

cli.md

errors.md

index.md

programmatic.md

watching.md

tile.json