0

I'm having a hard time trying to figure out how to error handle this piece of code.

This is the endpoint of my actix_web api, up until now everything works:

pub async fn simple_moving_average() -> HttpResponse {  
      if Client::new()
        .get("https://coinranking1.p.rapidapi.com/coins")
        .header(
        "X-RapidAPI-Key",
        "MY_KEY")
        .send()
        .await
        .is_err()
    {
        HttpResponse::BadRequest().finish();
    }
    HttpResponse::Ok().finish()
}

It's when I try to extract the data from the response that the compiler starts screaming at me:

[...]
let response = Client::new()
        .get("https://coinranking1.p.rapidapi.com/coins")
        .header(
        "X-RapidAPI-Key",
        "MY_KEY")
        .send()
        .await?
        .json::<Root>()
        .await?;
HttpResponse::Ok().finish()
}

cargo check ->

he ? operator can only be used in an async function that returns Result or Option (or another type that implements FromResidual) the trait FromResidual<Result<Infallible, reqwest::Error>> is not implemented for HttpResponserustcE0277 simple_moving_average.rs(50, 65): this function should return Result or Option to accept ?

Root in .json::<Root>() is just a struct representing json payload. I generated it from this website, not sure if it's relevant

how do I solve that? My final goal here would be to return a json response containing the data I get from this request. I've tried implementing the ::thiserror crate but I cannot figure out how it works and honestly I would prefer to understand how error handling works before using some fast solution.

I've tried following what compiler suggests but I cannot seem to solve the situation.

Jmb
  • 18,893
  • 2
  • 28
  • 55
amongosus
  • 45
  • 6
  • Please don't edit your question to include the answer. Instead you can [answer your own question](https://stackoverflow.com/help/self-answer). – Jmb Sep 29 '22 at 07:16

1 Answers1

0

I solved by using the dyn trait

correct code:

pub async fn simple_moving_average() -> 
Result<HttpResponse, Box<dyn std::error::Error>>{ [...] }
amongosus
  • 45
  • 6