Error Provide Carries Typed Payloads

Attach typed payloads like RetryInfo to errors with Error::provide and read them back via request_ref without downcasting.

RustResilience

Code

rustsnippet
48 lines
use std::error::{Error, Request};
use std::fmt;
use std::time::Duration;

#[derive(Debug)]
struct RetryInfo {
    after: Duration,
}

#[derive(Debug)]
enum FetchError {
    Throttled { info: RetryInfo },
    Forbidden,
}

impl fmt::Display for FetchError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FetchError::Throttled { .. } => write!(f, "throttled by the server"),
            FetchError::Forbidden => write!(f, "forbidden"),
        }
    }
}

impl Error for FetchError {
    // provide hands out typed payloads; request_ref pulls them back by type
    fn provide<'a>(&'a self, request: &mut Request<'a>) {
        if let FetchError::Throttled { info } = self {
            request.provide_ref(info);
        }
    }
}

fn plan_retry(err: &(dyn Error + 'static)) {
    match err.request_ref::<RetryInfo>() {
        Some(info) => println!("retry after {} ms", info.after.as_millis()),
        None => println!("no retry info attached"),
    }
}

fn main() {
    let throttled = FetchError::Throttled {
        info: RetryInfo { after: Duration::from_millis(750) },
    };
    println!("error: {throttled}");
    plan_retry(&throttled);
    plan_retry(&FetchError::Forbidden);
}

How it works

Error Provide Carries Typed Payloads is built around the functions fmt, provide, plan_retry and main.

Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.

Applying it

Signature: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result

Output lines are prefixed (retry after, no retry info attached, error:), making each step’s effect easy to spot.

main sequences plan_retry; executing the file runs that flow once.

Statements that matter

fn plan_retry(err: &(dyn Error + 'static)) {
    match err.request_ref::<RetryInfo>() {
        Some(info) => println!("retry after {} ms", info.after.as_millis()),
        None => println!("no retry info attached"),
    }
}
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
        FetchError::Throttled { .. } => write!(f, "throttled by the server"),
        FetchError::Forbidden => write!(f, "forbidden"),
    }
}
fn provide<'a>(&'a self, request: &mut Request<'a>) {
    if let FetchError::Throttled { info } = self {
        request.provide_ref(info);
    }
}

Interactive Tools for This Topic

FAQ

What does Error Provide Carries Typed Payloads print when run?
Execute the whole file; each printed line is prefixed with a label like `retry after`, `no retry info attached`, `error:`.