1

I'm new to rust, so, perhaps there's a way to do this that i'm not aware of, but, if I convert a reqwest::Body into a stream and invoke, for example, try_for_each_concurrent, the stream's Error type is reqwest::Error, so, I'm expected to return something of that type in the closure. But it is not possible, outside of the reqwest crate itself, to construct a reqwest::Error.

For example:

let mut stream = reqwest::get("http://httpbin.org/ip")
    .await?
    .bytes_stream();
let result = stream.try_for_each_concurrent(2, |c| async move {
  // This cannot work:
  let transformed = some_function_that_can_return_another_kind_of_error(c)?;
  // And there's no way to convert into a `reqwest::Error`, AFAIK
});

Since the types are out of my control, an alternative idea I had is to create a stream that consumes the stream from reqwest, but can't seem to find a simple way to do that. Is there a correct/idiomatic way of handling situations like this I'm not aware of?

Thanks for the help!

  • I have a similar issue, I would like to return my own error type but the lambda signature requires me to return tungstinite::Error in my case. Obviously, I can't extend that error to accept mine basically the same issue as you have. So have you found a solution to your problem? – Anton Dyachenko Jan 23 '23 at 04:33

1 Answers1

1

I think I found a solution to this problem. You need to convert err type before calling try_for_each_concurrent. Your example should look like

let mut stream = reqwest::get("http://httpbin.org/ip")
    .await?
    .bytes_stream();
let result = stream.err_into::<Your Error>()
    .try_for_each_concurrent(2, |c| async move {
let transformed = some_function_that_can_return_another_kind_of_error(c)?;

So it should work as is if "another_kind_of_error" implements into YourError type. If it doesn't you can manually convert using

let transformed = some_function_that_can_return_another_kind_of_error(c).
    map_err(|e| { conversion })?

So in this case your lambda could return both underlying reqwest::Error and your own error packed into wrapper enum error YourError. I have used thiserror::Error to get rid of the boilerplate for making this wrapper error enum.

Anton Dyachenko
  • 169
  • 1
  • 9