In this lesson, you will learn how to leverage the Result type and custom traits to encode systemic recovery strategies directly into your type system.
Beyond Simple Propagation
Up until now, you have likely used the ? operator to bubble errors up to the caller. While efficient, this is essentially "giving up" and passing the buck. In robust systems, we often want to define how an error should be handled at the type level. We can achieve this by defining a trait that describes recovery capabilities and implementing it for specific error variants.
Consider a system where we might face a Transient network error or a Fatal configuration error. Instead of treating all errors as opaque, we can define a Recoverable trait:
trait Recoverable {
fn attempt_recovery(&self) -> bool;
}
enum NetworkError {
Transient,
Fatal,
}
impl Recoverable for NetworkError {
fn attempt_recovery(&self) -> bool {
match self {
NetworkError::Transient => {
println!("Retrying connection...");
true
}
NetworkError::Fatal => false,
}
}
}
Type-Driven Strategy
By binding our functions to types that implement Recoverable, we move away from Result<T, E> being a "bag of errors" and turn it into a state machine. You can create a function that forces a recovery attempt before the program is allowed to proceed:
fn execute_with_recovery<T, E: Recoverable>(result: Result<T, E>) -> Option<T> {
match result {
Ok(val) => Some(val),
Err(err) => {
if err.attempt_recovery() {
// Here you would trigger your retry logic
None
} else {
panic!("Unrecoverable error encountered!");
}
}
}
}
By encoding recovery strategies into the trait, the compiler ensures that every error type passing through your system knows exactly how to respond to failure. This prevents "error swallowing" and forces developers to explicitly handle the lifecycle of an error rather than just propagating it blindly.
Key Takeaway: By implementing recovery traits for your error variants, you transform opaque errors into active participants in the system's resilience, allowing the compiler to enforce documented recovery strategies.