← 中文资源

简体中文版本

Error::provide 携带类型化载荷

用 Error::provide 把 RetryInfo 这类类型化载荷挂到错误上,消费端通过 request_ref 按类型直接取回,绕开 downcast。

阅读英文原文

实现说明

逻辑集中在函数 fmt、provide、plan_retry、main里。 通过 match 做模式匹配,值的每种形态都必须被处理。

使用要点

  • 演示输出是带标签的(retry after、no retry info attached、error:),每个操作都会留下自己的一行标注。
  • 执行文件,main 会按顺序走完 plan_retry。

常见问题

运行「Error::provide 携带类型化载荷」会打印什么?

运行文件本身,retry after、no retry info attached、error: 这些前缀各对应一段演示逻辑。

主要签名是 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result

核心语句

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);
    }
}

代码示例

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);
}