Error handling.
This commit is contained in:
parent
a9d5459cb4
commit
e3946c8129
3 changed files with 181 additions and 9 deletions
26
src/main.rs
26
src/main.rs
|
@ -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"))
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue