Error handling.

This commit is contained in:
Lyle Mantooth 2023-05-13 16:24:05 -04:00
parent a9d5459cb4
commit e3946c8129
Signed by: IslandUsurper
GPG key ID: 6DB52EAE123A5789
3 changed files with 181 additions and 9 deletions

View file

@ -2,11 +2,18 @@ use serde::Deserialize;
#[tokio::main]
async fn main() {
let res = reqwest::get("https://api.thecatapi.com/v1/images/search")
.await
.unwrap();
let url = get_cat_image_url().await.unwrap();
println!("The image is at {}", url);
}
async fn get_cat_image_url() -> color_eyre::Result<String> {
let api_url = "https://api.thecatapi.com/v1/images/search";
let res = reqwest::get(api_url).await?;
if !res.status().is_success() {
panic!("Request failed with HTTP {}", res.status());
return Err(color_eyre::eyre::eyre!(
"The Cat API returned HTTP {}",
res.status()
));
}
#[derive(Deserialize)]
@ -14,9 +21,10 @@ async fn main() {
url: String,
}
let images: Vec<CatImage> = res.json().await.unwrap();
let image = images
.first()
.expect("the cat API should return at least one image");
println!("The image is at {}", image.url);
let mut images: Vec<CatImage> = res.json().await?;
if let Some(image) = images.pop() {
Ok(image.url)
} else {
Err(color_eyre::eyre::eyre!("The Cat API returned no images"))
}
}