From d3d199b42ac694191255f81861dca2e368a90d66 Mon Sep 17 00:00:00 2001 From: Adrian Malacoda Date: Sun, 3 Dec 2017 23:56:35 -0600 Subject: [PATCH] implement proper api error handling --- src/lib.rs | 42 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 32d49fe..a358189 100644 --- a/src/lib.rs +++ b/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, + pub warnings: Option> +} + +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)]