Expected struct `anyhow::Error`, found struct `JoinError` when trying to join a spawned tokio task

Thank you for taking the time to read my query. I'm trying to join 2 async functions; device_to_endpoint and health. My main function returns a anyhow::Result<()>. When I try to do try_join!, I get the error:

--> coap-endpoint/src/main.rs:210:5
    |
210 |     futures::try_join!(health.run_ntex(), device_to_endpoint)?;
    |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `anyhow::Error`, found struct `JoinError`
    |
    = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

I saw this post where the OP had the same issue, and the solution was to use map_err. However this didn't work for me. I even made sure that JoinError implemented std::error::Error. Any help would be much appreciated!

Here is the problematic part of my code:

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    .
    .
    .
    let device_to_endpoint = tokio::spawn(async move {
        let mut server = Server::new(addr).unwrap();
        server
            .run(|request| publish_handler(request, app.clone()))
            .await;
    });

    let health = HealthServer::new(config.health, vec![]);

    futures::try_join!(health.run_ntex(), device_to_endpoint)?;

    Ok(())
}

In this case the problem is that try_join! requires both halves to use the same error type, but they do not in this case. One way to fix it is the following:

futures::try_join!(
    health.run_ntex(),
    async move {
        device_to_endpoint.await.map_err(anyhow::Error::from)
    },
)?;
4 Likes

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.