implement proper api error handling
This commit is contained in:
parent
58104d616b
commit
d3d199b42a
42
src/lib.rs
42
src/lib.rs
@ -7,6 +7,9 @@ extern crate reqwest;
|
||||
use std::collections::HashMap;
|
||||
use std::io::Read;
|
||||
|
||||
use std::fmt;
|
||||
use std::fmt::{Display, Formatter};
|
||||
|
||||
pub struct Scryfall {}
|
||||
|
||||
impl Scryfall {
|
||||
@ -18,7 +21,16 @@ impl Scryfall {
|
||||
let mut response = reqwest::get(&format!("https://api.scryfall.com/cards/search?q={}", query))?;
|
||||
let mut content = String::new();
|
||||
response.read_to_string(&mut content);
|
||||
Result::Ok(serde_json::from_str(&content)?)
|
||||
|
||||
match serde_json::from_str(&content) {
|
||||
Ok(list) => Ok(list),
|
||||
Err(error) => {
|
||||
match serde_json::from_str(&content) {
|
||||
Ok(api_error) => Err(Error::API(api_error)),
|
||||
Err(_) => Err(Error::Parse(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -113,7 +125,33 @@ pub enum Error {
|
||||
/// HTTP request failed
|
||||
HTTP(reqwest::Error),
|
||||
/// Failed to parse
|
||||
Parse(serde_json::Error)
|
||||
Parse(serde_json::Error),
|
||||
/// Error from API
|
||||
API(APIError)
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct APIError {
|
||||
pub status: i32,
|
||||
pub code: String,
|
||||
pub details: String,
|
||||
pub error_type: Option<String>,
|
||||
pub warnings: Option<Vec<String>>
|
||||
}
|
||||
|
||||
impl std::error::Error for APIError {
|
||||
fn description(&self) -> &str {
|
||||
&self.details
|
||||
}
|
||||
fn cause(&self) -> Option<&std::error::Error> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for APIError {
|
||||
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
|
||||
write!(f, "{}", self.details)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
Loading…
x
Reference in New Issue
Block a user