rust 我想按匹配处理响应中的错误

dy2hfwbg  于 2023-02-04  发布在  其他
关注(0)|答案(1)|浏览(138)

我通过服务器收到响应,当我使用match处理错误时,我在操作过程中收到错误,我不知道如何解决该错误,请帮助

let host_clint = Client::new();
let response = host_clint
    .post("https://xnbng--80ak6aa92e.com")
    .form(&hashmap)
    .send()?;

let respose_req = match response.json::<USER>(){
    Ok(data) => data,
    Err(err) => {
        println!("Error while receiving response body: {}", err);

    }
};


Error:
error[E0308]: `match` arms have incompatible types
   --> src\main.rs:268:13
    |
265 |     let respose_req = match response.json::<USER>(){
    |                       ----------------------------------- `match` arms have incompatible types
266 |         Ok(data) => data,
    |                     ---- this is found to be of type `USER`
267 |         Err(err) => {
268 |             println!("Error while receiving response body: {}", err);
    |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `USER`, found `()`
    |
    = note: this error originates in the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
qpgpyjmq

qpgpyjmq1#

如果使用match将值赋给变量,则必须在两个匹配条件中返回相同类型的值。Ok条件返回user类型的数据,但Err条件只将一行打印到stdout,而不返回可赋给response_req的值。

let respose_req = match response.json::<USER>(){
    Ok(data) => data,  // <-- Returns the value from 'data' of type USER
    Err(err) => {
        println!("Error while receiving response body: {}", err); // <-- Returns nothing, just prints a line to the stdout
   }
};

所以,你必须在每个匹配条件中返回一些'user'类型的值,但是我建议把它 Package 成一个选项,如下所示:

let respose_req: Option<USER> = match response.json::<USER>(){
    Ok(data) => Some(data),  
    Err(err) => {
        println!("Error while receiving response body: {}", err);
        None
   }
};

或者你可以这样处理这个错误:

let response_req = response.json::<USER>();
if let Err(err) = response_req {
    println!("Error while receiving response body: {}", err);
    // here you have to prevent your code from further execution by using break or return.
}

// now you can just safely unwrap response_req whenever you use it because the error case is already handled.
response_req.unwrap().DO_SOME_STUFF()

相关问题