How to match &dyn Error type?

I'm trying to match &dyn Error type to skip the logging.
I get the websock:151 Failed to recv message from ws: WebSocket protocol error: Connection reset without closing handshake error in the log but my downcast_ref method fails and fails to catch this specific error. how am i supposed to catch the error appropriately?

 while let Some(message) = ws_rx.next().await {
        let msg = match message {
            Ok(msg) => msg,
            Err(e) => {
                // ResetWithoutClosingHandshake just means that client has disconnected.
                // Skip the logging and break the loop.
                if let Some(e) = e.source() {
                    match e.downcast_ref::<tungstenite::error::Error>() {
                        Some(tungstenite::Error::Protocol(
                            ProtocolError::ResetWithoutClosingHandshake,
                        )) => break,
                        _ => (),
                    };
                }
                log_error!("Failed to recv message from ws: {e}");
                continue;
            }
        };

There's not enough context from just this snippet.

I'd need to see at least the imports or maybe the whole file so that I know what types are being used for sure.

My guess is the e on line 4 is already of type tungstenite::error::Error so you would just match on that instead of trying to downcast. If it's a std::error::Error then maybe you could call downcast on that instead of calling source then downcast.

1 Like

Type of e is warp::Error from warp error doc

/// Errors that can happen inside warp.
pub struct Error {
    inner: BoxError,
}

and its source() function returns dyn StdError.


impl StdError for Error {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        Some(self.inner.as_ref())
    }
}

I'm not sure. It's probably another error type or there's another struct wrapping it. Currently you're printing the error with display. If you print the error with debug formatting ( using {:?} ) it might print out enough of the type name for you to figure it out.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.