Shared futures and anyhow Errors

Hi,

I have (in a tokio context) the need for pre-loading some data in the context of a request that later in the request will be used by mutiple different tasks.

Is the way shown in the code a good way to achive:

  • Less verbose code than spraying Shared, Box, Pin etc. all over
  • A way to "transfer" the anyhow::Error in Shared futures (it's note clone so cannot use it directly)'
  • Starting of the work to pre-load straigt away when run_shr(..) is called, before it is awaited

Or is there a better / more standard way to sachive this?

Any pointers apprechiated

/V

For this, I'd map the anyhow::Error in Arc to make it shared. This means it's possible to get at things like the backtrace and the underlying error chain if you later need that, without a huge amount of refactoring to include them in ShrError.

Otherwise, this looks like how I'd expect you to meet your goals; the type alias reduces the volume of code you write, and spawning means that the work is driven to completion as soon as possible - even if no-one is waiting for it to finish.

You might also decide that you don't want to expose the task failure state at all; you've arranged that the spawned task can't be cancelled, and you might decide that you're happier propagating a panic if the task panics, which then avoids the need for ShrError::JoinError to be exposed.

Thanks for the pointers.

You refered to wrapping arnyhow::Error in an Arc<> which is actually whee I started. But I quickly run into problems since Arcanyhow::Error does not implement std:Error and that's why I did the workaround here.

I like your way of actually including the anyhow in an Arc inside a new type though - it's still not ideal (I assume?) in that if I use ? to propagate the error in a function returning a anyhow::Error it will create a wrapper of ShrError and will thus not directly hace the chain/context - but I see your point that I can then retrieve it by matching on the ShrError type.

It's a shame that there is no easy way to create a anyhow::Error from a Arcanyhow::Error that gives be the context/chain..

Thanks again

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.