All files / src error-handler.js

91.18% Statements 300/329
87.3% Branches 55/63
100% Functions 20/20
91.18% Lines 300/329

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 3591x 1x 1x 1x   1x 1x   1x 1x 1x 1x 1x 33x 33x 33x 33x 33x 33x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 1x   1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 1x   1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 1x   1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 1x   1x 1x 1x 1x 1x 58x 58x 58x   1x 1x 1x 1x 11x 4x 4x 4x   7x 7x 7x   7x 11x             7x 11x 5x 5x 5x   7x 11x 4x 4x 4x   11x     11x   1x 1x 1x 1x 29x 29x   29x 29x 1x 1x 1x 1x 1x 1x 1x 29x 1x 1x 1x 1x 1x 1x 1x 1x 1x 28x 1x 1x 1x 1x 1x 1x 1x 27x 2x 2x 2x 1x 1x 26x 24x 24x 24x       24x       24x 24x           24x       24x         24x 24x 4x 4x 4x 4x 4x 24x 24x   29x 29x   1x 1x 1x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x   1x 1x 1x 1x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x   1x 1x 1x 1x 5x 5x 5x 5x 4x 4x 4x 4x 4x 4x 5x 5x   1x 1x 1x 1x 5x 5x 5x 5x 4x 4x 4x 4x 4x 4x 5x 5x   1x 1x 1x 1x 6x 3x 3x 6x   1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 2x   1x 1x 1x 1x 4x 1x 1x 4x   1x 1x 1x 1x 4x 1x 1x 4x   1x 1x 1x 1x 4x 1x 1x 4x 1x   1x 1x 1x 1x 11x     11x   11x     11x 11x   1x 1x 1x 1x 9x 9x  
/**
 * Enhanced error handling system for git-ingest
 * Provides consistent error types, messages, and handling strategies
 */
 
import path from "path";
import { theme } from "./theme.js";
 
/**
 * Base error class for git-ingest specific errors
 */
export class GitIngestError extends Error {
  constructor(message, code = "GENERIC_ERROR", details = {}) {
    super(message);
    this.name = "GitIngestError";
    this.code = code;
    this.details = details;
    this.timestamp = new Date().toISOString();
  }
 
  toJSON() {
    return {
      name: this.name,
      message: this.message,
      code: this.code,
      details: this.details,
      timestamp: this.timestamp,
      stack: this.stack
    };
  }
}
 
/**
 * Directory-related errors
 */
export class DirectoryError extends GitIngestError {
  constructor(message, path, originalError = null) {
    super(message, "DIRECTORY_ERROR", {
      path,
      originalError: originalError?.message
    });
    this.name = "DirectoryError";
    this.path = path;
    this.originalError = originalError;
  }
}
 
/**
 * File processing errors
 */
export class FileProcessingError extends GitIngestError {
  constructor(message, filePath, originalError = null) {
    super(message, "FILE_PROCESSING_ERROR", {
      filePath,
      originalError: originalError?.message
    });
    this.name = "FileProcessingError";
    this.filePath = filePath;
    this.originalError = originalError;
  }
}
 
/**
 * Configuration errors
 */
export class ConfigurationError extends GitIngestError {
  constructor(message, option = null, value = null) {
    super(message, "CONFIGURATION_ERROR", { option, value });
    this.name = "ConfigurationError";
    this.option = option;
    this.value = value;
  }
}
 
/**
 * Resource limit errors
 */
export class ResourceLimitError extends GitIngestError {
  constructor(message, resource, limit, actual) {
    super(message, "RESOURCE_LIMIT_ERROR", { resource, limit, actual });
    this.name = "ResourceLimitError";
    this.resource = resource;
    this.limit = limit;
    this.actual = actual;
  }
}
 
/**
 * Error handler class with enhanced formatting and suggestions
 */
export class ErrorHandler {
  constructor(options = {}) {
    this.verbose = options.verbose || false;
    this.quiet = options.quiet || false;
  }
 
  /**
   * Handle and format errors for display
   */
  handle(error, exitProcess = false) {
    if (this.quiet) {
      if (exitProcess) process.exit(1);
      return;
    }
 
    // Format error message
    const formattedError = this.formatError(error);
    console.error(formattedError.message);
 
    // Show suggestions if available
    if (formattedError.suggestions.length > 0) {
      console.error(theme.warning("\nšŸ’” Suggestions:"));
      formattedError.suggestions.forEach((suggestion, index) => {
        console.error(theme.warning(`   ${index + 1}. ${suggestion}`));
      });
    }
 
    // Show stack trace in verbose mode
    if (this.verbose && error.stack) {
      console.error(theme.muted("\nStack trace:"));
      console.error(theme.muted(error.stack));
    }
 
    // Show additional details for custom errors
    if (error instanceof GitIngestError && this.verbose) {
      console.error(theme.muted("\nError details:"));
      console.error(theme.muted(JSON.stringify(error.details, null, 2)));
    }
 
    if (exitProcess) {
      process.exit(1);
    }
  }
 
  /**
   * Format error message with icon and color
   */
  formatError(error) {
    const message = theme.error("āŒ Error: ") + error.message;
    const suggestions = [];
 
    // Add specific formatting and suggestions based on error type
    if (error instanceof DirectoryError) {
      suggestions.push("Verify the directory path exists and is accessible");
      suggestions.push("Check file system permissions");
      if (error.path) {
        suggestions.push(
          `Try using an absolute path: ${path.resolve(error.path)}`
        );
      }
    } else if (error instanceof FileProcessingError) {
      suggestions.push(
        "Check if the file is corrupted or in use by another process"
      );
      suggestions.push("Verify file permissions");
      if (error.filePath) {
        suggestions.push(
          `Try excluding this file with --exclude "${path.basename(error.filePath)}"`
        );
      }
    } else if (error instanceof ConfigurationError) {
      suggestions.push("Review the command line options");
      suggestions.push("Check the configuration file syntax if using --config");
      if (error.option && error.value) {
        suggestions.push(
          `Invalid value "${error.value}" for option "${error.option}"`
        );
      }
    } else if (error instanceof ResourceLimitError) {
      suggestions.push(`Consider increasing the ${error.resource} limit`);
      suggestions.push("Try excluding large files or directories");
      if (error.resource === "memory") {
        suggestions.push("Process smaller directories at a time");
      }
    } else {
      // Handle Node.js system errors
      switch (error.code) {
        case "ENOENT":
          suggestions.push("Verify the file or directory exists");
          suggestions.push("Check for typos in the path");
          break;
        case "EACCES":
          suggestions.push("Check file/directory permissions");
          suggestions.push("Run with appropriate user privileges");
          break;
        case "EMFILE":
        case "ENFILE":
          suggestions.push(
            "Too many open files - try processing smaller directories"
          );
          suggestions.push("Increase system file descriptor limits");
          break;
        case "ENOSPC":
          suggestions.push("Insufficient disk space");
          suggestions.push("Free up disk space and try again");
          break;
        case "ENOMEM":
          suggestions.push("Insufficient memory");
          suggestions.push("Try processing smaller directories");
          suggestions.push("Increase system memory or reduce --max-size limit");
          break;
        default:
          if (error.message.includes("clipboard")) {
            suggestions.push("Install clipboard tools for your platform:");
            suggestions.push("  macOS: pbcopy (built-in)");
            suggestions.push("  Linux: xclip or xsel");
            suggestions.push("  Windows: clip (built-in)");
          }
      }
    }
 
    return { message, suggestions };
  }
 
  /**
   * Wrap async functions with error handling
   */
  async wrapAsync(fn, context = "operation") {
    try {
      return await fn();
    } catch (error) {
      throw new GitIngestError(
        `Failed to ${context}: ${error.message}`,
        "WRAPPED_ERROR",
        {
          context,
          originalError: error.message
        }
      );
    }
  }
 
  /**
   * Wrap async functions with error handling
   */
  safeAsyncWrapper(fn, context = "operation") {
    return async (...args) => {
      try {
        return await fn(...args);
      } catch (error) {
        throw new GitIngestError(
          `Failed to ${context}: ${error.message}`,
          "WRAPPED_ERROR",
          {
            context,
            originalError: error.message
          }
        );
      }
    };
  }
 
  /**
   * Create a safe wrapper for file operations
   */
  safeFileOperation(operation, filePath) {
    return async (...args) => {
      try {
        return await operation(...args);
      } catch (error) {
        throw new FileProcessingError(
          `Failed to process file: ${error.message}`,
          filePath,
          error
        );
      }
    };
  }
 
  /**
   * Create a safe wrapper for directory operations
   */
  safeDirectoryOperation(operation, dirPath) {
    return async (...args) => {
      try {
        return await operation(...args);
      } catch (error) {
        throw new DirectoryError(
          `Failed to access directory: ${error.message}`,
          dirPath,
          error
        );
      }
    };
  }
 
  /**
   * Validate and throw configuration error if invalid
   */
  validateConfig(condition, message, option = null, value = null) {
    if (!condition) {
      throw new ConfigurationError(message, option, value);
    }
  }
 
  /**
   * Check resource limits and throw error if exceeded
   */
  checkResourceLimit(actual, limit, resource) {
    if (actual > limit) {
      throw new ResourceLimitError(
        `${resource} limit exceeded: ${actual} > ${limit}`,
        resource,
        limit,
        actual
      );
    }
  }
 
  /**
   * Log warning message
   */
  warn(message) {
    if (!this.quiet) {
      console.warn(theme.warning("āš ļø  Warning: ") + message);
    }
  }
 
  /**
   * Log info message
   */
  info(message) {
    if (!this.quiet) {
      console.log(theme.blue("ā„¹ļø  Info: ") + message);
    }
  }
 
  /**
   * Log success message
   */
  success(message) {
    if (!this.quiet) {
      console.log(theme.green("āœ… ") + message);
    }
  }
}
 
/**
 * Global error handlers for uncaught exceptions
 */
export function setupGlobalErrorHandlers(errorHandler) {
  process.on("uncaughtException", (error) => {
    console.error(theme.error("šŸ’„ Uncaught Exception:"));
    errorHandler.handle(error, true);
  });
 
  process.on("unhandledRejection", (error) => {
    console.error(theme.error("šŸ’„ Unhandled Rejection:"));
    errorHandler.handle(error, true);
  });
}
 
/**
 * Utility function to create error handler with options
 */
export function createErrorHandler(options = {}) {
  return new ErrorHandler(options);
}