Incompatible Errors when Spawning Async Functions

I have an async function with this signature:

pub async fn accwrite(acc:&AccStruct) -> 	Result<bool, anyhow::Error> {...

It runs fine in a single threaded async environment, its future executed by try_join!.
However, when I try to spawn it off with:

use tokio::task;
let acf = task::spawn(accwrite(&acc)); 

I get incompatible error types:

let (_tres,_acres,_tbres,_prres) = try_join!(trf,acf,tbf,prf).unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct anyhow::Error, found struct tokio::runtime::task::error::JoinError

I thought that anyhow::Error got me out of the error hell but it seems not. Is there any (simple) way of solving this please?

1 Like

spawn can fail in its own unique way, so you need task::spawn(…)? or task::spawn(…).unwrap() or such to handle the spawning error before you handle error from the spawned future.


check signature of task::spawn first before considering return type of accwrite
It's future returns Result<T, JoinError> where T is your's Result<bool, anyhow::Error>

Given that anyhow::Error is a catch-all error type that can be created from anything, I'd recommend working around this with:

let acf = task::spawn(accwrite(&acc)).map_err(anyhow::Error::from);

try_join! seems to require all error types to match, and this converts task::spawn's error into anyhow::Error.


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.