Course contentsShow
← Rust
Lesson 879 of 1,9107. Error Handling PatternsFree lesson

Centralized Error Resolution Policies

Define a project-wide standard for classifying recoverable and unrecoverable states.

In this lesson, you will learn how to define a project-wide standard for classifying recoverable and unrecoverable states to ensure consistent error resolution across your codebase.

When building complex systems, developers often struggle with a fundamental question: "Should I return an error, or should I panic?" Without a centralized policy, one module might attempt to retry a transient failure while another crashes the process for the exact same condition. A Centralized Error Resolution Policy acts as your system's "constitutional document" for handling failures.

The Categorization Standard

To implement this, you must explicitly categorize every failure point into two buckets:

  1. Recoverable Errors: Expected conditions (like network timeouts or invalid user input). These must implement std::error::Error and be propagated via Result. The policy mandates that these must be handled by the caller or bubbled up to a boundary where they can be logged.
  2. Unrecoverable States: Logic bugs, invariant violations (like a Mutex being poisoned), or resource exhaustion that prevents the process from functioning. These violate the contract of the application and should be addressed via panic! or an abort mechanism.

Applying the Policy

Consider a service that processes incoming data. Your policy might look like this:

pub enum AppError {
    // Recoverable: Client can retry these
    TransientNetworkFailure(String),
    ValidationError(String),
    
    // Unrecoverable: Indicates a bug or memory corruption
    InternalInvariantViolated(String), 
}

// Resolution Logic
fn handle_error(err: AppError) {
    match err {
        AppError::TransientNetworkFailure(_) | AppError::ValidationError(_) => {
            log::warn!("Recoverable error occurred: {:?}", err);
            // Logic to retry or ask user for input
        }
        AppError::InternalInvariantViolated(msg) => {
            // Centralized policy: Unrecoverable states must be escalated
            panic!("Critical system invariant violated: {}", msg);
        }
    }
}

By centralizing this, you prevent "hidden" logic where one developer silently swallows a fatal error while another incorrectly panics over a simple timeout. When a new team member joins, they don't have to guess how to handle a Result; they look at the policy to see if their error type is classified as a recoverable domain event or a fatal system failure.

Key Takeaway: A Centralized Error Resolution Policy establishes a strict binary between recoverable domain errors that warrant retry/user-feedback and unrecoverable invariant violations that mandate termination.