unwrap_err() function seems to be returning T rather than E

723 Views Asked by At

I am trying to handle possible errors from a websocket connection this way:

        let connection: Result<Client<TlsStream<TcpStream>>,WebSocketError>
                = client_builder.unwrap().connect_secure(Some(tls_connector.unwrap()));

        if connection.is_err() {
                println!("Error: {}", connection.unwrap_err());
        }

The error I am getting is the following:

error[E0277]: `websocket::sync::Client<native_tls::TlsStream<std::net::TcpStream>>` doesn't implement `Debug`
  --> src/main.rs:29:25
   |
29 |         println!("Error: {}", connection.as_ref().unwrap_err());    
   |                               ^^^^^^^^^^^^^^^^^^^ ---------- required by a bound introduced by this call
   |                               |
   |                               `websocket::sync::Client<native_tls::TlsStream<std::net::TcpStream>>` cannot be formatted using `{:?}` because it doesn't implement `Debug`
   |
   = help: the trait `Debug` is not implemented for `websocket::sync::Client<native_tls::TlsStream<std::net::TcpStream>>`
   = note: required for `&websocket::sync::Client<native_tls::TlsStream<std::net::TcpStream>>` to implement `Debug`
note: required by a bound in `Result::<T, E>::unwrap_err`

This is rather strange to me because unwrap_err() should be returning a WebSocketError enum not websocket::sync::Client<native_tls::TlsStreamstd::net::TcpStream> which rightly so has no Debug implementation

I have tried the different unwrap functions but to be honest I need the unwrap_err() one.

2

There are 2 best solutions below

0
On BEST ANSWER

unwrap_err will print the value inside of Ok in it's panic message, so it still requires Debug for T. If you can't satisfy that you can use if let:

if let Err(e) = connection {
    println!("Error: {}", e);
}
0
On

unwrap_err will panic if the Result in question is not of the Err variant. It panics with a message that includes the Ok value, which requires that T implements Debug.

Instead of checking manually with is_err, you should use if let like so:

if let Err(e) = connection.as_ref() {
    println!("Error: {}", e);
}