error-handling - 如何处理生锈的盒装和连锁错误?
问题描述
我有很多代理 uri(http 和 socks5),我正在使用 reqwest 通过这些代理发送一些 http 请求,如果他不工作,我想删除一个代理。
for proxy in proxies {
let proxy = match Proxy::all(proxy_url) {
Ok(proxy) => proxy,
Err(e) => {
eprintln!("creating proxy failed! {:?}", e);
continue;
}
};
let client = match Client::builder()
.proxy(proxy)
.build()
let client = match client {
Ok(client) => client,
Err(e) => {
eprintln!("building client failed! {:?}", e);
continue;
}
}
loop {
match client.get(&config.endpoint).send().await {
Ok(_) => {}
Err(e) => {
if e.is_proxy_error() { // this method doesn't exist
eprintln!("Dropping proxy...");
break;
} else {
eprintln!("client error! {:?}", e);
}
}
}
}
}
我有很多种Reqwest::Error
reqwest::Error { kind: Request, url: "http://example.com/", source: hyper::Error(Connect, "socks connect error: Invalid response version") }
reqwest::Error { kind: Request, url: "http://example.com/", source: hyper::Error(Connect, "socks connect error: Proxy server unreachable") }
reqwest::Error { kind: Request, url: "http://example.com/", source: hyper::Error(Connect, "socks connect error: Connection refused") }
reqwest::Error { kind: Request, url: "http://example.com/", source: hyper::Error(Connect, "socks connect error: Connection reset by peer (os error 104)") }
在大多数情况下,错误消息是明确的,但我怎样才能以不同的方式处理它们?reqwest::Error
haveinner
字段是私有的,所以我无法访问他。如果我得到了的来源reqwest::Error
,我只是有一个Box<syn Error>
我不能像对待hyper::Error
解决方案
您可以将结果向下转换为Error::source()
具体的错误类型,例如
use std::error::Error;
...
Err(reqwest_error) => {
let hyper_error: Option<&hyper::Error> = reqwest_error
.source()
.unwrap()
.downcast_ref();
...
}
此代码用于unwrap()
从Option
返回的中提取错误source()
。如果你不能保证错误总是有来源,你应该使用一些有条件的方式来解开来源,例如
let hyper_error: Option<&hyper::Error> = reqwest_error
.source()
.and_then(|e| e.downcast_ref());
推荐阅读
- python - 当我用烧瓶运行它时,它一直显示 {% for post in all_posts %} 和 {% endfor %} 的未知标签错误
- python - 轻松将垂直线添加到 pandas plot.bar() 时间序列数据
- reactjs - React 提交 post 请求并打开它的 application/pdf 响应
- javascript - 在页面内搜索并删除其他内容
- typescript - DHX 调度程序未定义
- ios - 是否可以在我的 iOS swift 中将 App Tracking Tranparency 的默认值设置为 .denied
- xamarin - Xamarin Forms - 将函数绑定到 StackLayout TapGesture
- python - TypeError:timedelta days 组件不支持的类型:dict
- r - R 热图,将颜色更改为我想要的比例。热图
- jquery - 在新标签页中打开链接在 Safari iOS 上不起作用