version: 1
kind: rule
name: Error Handling Rule
description: Comprehensive error handling strategies for robust, resilient applications with proper logging and user experience
prompt: |
  Implement typed exceptions, graceful degradation, and proper logging for system resilience.
  Provide user-friendly error messages and introduce retry mechanisms and circuit breakers.
  Clearly classify errors (system, business logic, validation) and define severity levels.
  Log all errors in a structured format and monitor them by integrating with tracking systems.
enhanced-prompt: |-
  ### Error Handling Principles
  - **Error Classification**: Clearly classify errors into five categories: System (infrastructure), Business Logic (domain), Validation (input), Security (auth), and External Service (API).
  - **Severity Levels**: Prioritize responses by assigning severity levels: Critical (immediate action), Error (functional failure), Warning (potential issue), and Info (informational).

  ### Typed Error Handling
  - **Custom Error Classes**: Create a base error class like `TaskActionError` and extend it to define specific error types such as `ValidationError` and `ConfigurationError`. This clarifies the origin and nature of errors.
  - **Result Pattern**: Wrap `try-catch` blocks in a `Result` object (containing `data` on success or `error` on failure) to explicitly handle success and failure cases in function signatures, improving predictability.

  ### Error Handling Strategies
  - **Graceful Degradation**: Design systems so that if a core feature fails, the service can continue operating with auxiliary functions or alternative paths. For instance, if one notification channel fails, try the next one.
  - **Retry Mechanisms**: Implement retry logic with exponential backoff for transient network issues or external service failures to enhance system stability. Clearly define retry conditions and maximum attempts.
  - **Circuit Breaker Pattern**: Temporarily block calls to external services that are repeatedly failing to prevent system-wide failure propagation. Manage 'Closed', 'Open', and 'Half-Open' states to attempt recovery automatically.

  ### Logging & Monitoring
  - **Structured Logging**: Log all entries in a structured format like JSON for easy searching and analysis. Include consistent context like `level`, `timestamp`, `requestId`, and `userId`.
  - **Error Tracking Integration**: Integrate with services like Sentry or Datadog to aggregate and analyze errors centrally. Always filter sensitive information before transmission to maintain security.

  ### User Experience
  - **User-Friendly Messages**: Provide clear, concise error messages that do not expose internal implementation details. Instead of "An error occurred," offer specific guidance like "Invalid email format."
