【问题标题】:Detecting a ConnectionReset in Rust, instead of having the Thread panic在 Rust 中检测 ConnectionReset,而不是让线程恐慌
【发布时间】:2021-02-11 21:05:59
【问题描述】:

所以我在 Rust 中有一个多线程程序,它向我的网站发送 Get 请求,我想知道如何检测 ConnectionReset。 我要做的是,在请求之后,检查是否有 ConnectionReset,如果有,请等待一分钟,这样线程就不会恐慌

我现在使用的代码

let mut req = reqwest::get(&url).unwrap();

在执行完之后,我想检查是否有 ConnectionReset,然后 println(“连接错误”),而不是让线程恐慌。

我要检测的错误

thread '<unnamed>' panicked at 'called `Result::unwrap()` on an `Err` value: 
Error { kind: Io(Custom { kind: Other, error: Os { code: 10054, kind: ConnectionReset, 
message: "An existing connection was forcibly closed by the remote host." } }), 
url: Some("https://tayhay.vip") }', src\main.rs:22:43

我还阅读了一些关于 std::panic::catch_unwind 的内容,但我不确定这是否是正确的方法。

【问题讨论】:

  • 通过调用 .unwrap() 你明确告诉 Rust 恐慌。

标签: rust reqwest


【解决方案1】:

.unwrap 字面意思是:“发生错误时的恐慌”。如果您不想惊慌,则必须自己处理错误。根据您未向我们展示的代码,您可以在这里找到三种解决方案:

  1. 使用? operator 向上传播错误并让调用函数处理它。
  2. 准备好一些默认值以备出现错误时使用(或即时创建):
let mut req = reqwest::get (&url).unwrap_or (default);

let mut req = reqwest::get (&url).unwrap_or_else (|_| { default });

(这可能不适用于这种特定情况,因为我不知道这里的默认设置是什么,但它适用于其他错误处理情况)。

  1. 有一些特定的错误处理代码:
match reqwest::get (&url) {
   Ok (mut req) => { /* Process the request */ },
   Err (e) => { /* Handle the error */ },
}

有关更多详细信息,Rust 书有完整的chapter on error handling

【讨论】:

    猜你喜欢
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    相关资源
    最近更新 更多