From eab31e5e913f4a05c5590cbe8a28de168400740c Mon Sep 17 00:00:00 2001 From: Jef Roosens Date: Sun, 4 Apr 2021 13:03:08 +0200 Subject: [PATCH] [#9] Added general error module --- src/errors.rs | 23 +++++++++++++++++++++++ src/ivago/controller/search.rs | 3 ++- src/ivago/mod.rs | 7 +++---- src/main.rs | 1 + 4 files changed, 29 insertions(+), 5 deletions(-) create mode 100644 src/errors.rs diff --git a/src/errors.rs b/src/errors.rs new file mode 100644 index 0000000..6403235 --- /dev/null +++ b/src/errors.rs @@ -0,0 +1,23 @@ +use reqwest::Error; +use rocket::http::Status; + +pub enum FejError { + InvalidArgument, + FailedRequest, +} + +impl From for Status { + fn from(err: FejError) -> Status { + match err { + FejError::InvalidArgument => Status::BadRequest, + FejError::FailedRequest => Status::InternalServerError, + } + } +} + +// TODO make this more advanced where possible +impl From for FejError { + fn from(_: Error) -> FejError { + FejError::FailedRequest + } +} diff --git a/src/ivago/controller/search.rs b/src/ivago/controller/search.rs index be81254..926d282 100644 --- a/src/ivago/controller/search.rs +++ b/src/ivago/controller/search.rs @@ -1,3 +1,4 @@ +use crate::errors::FejError; use regex::Regex; use reqwest::blocking as reqwest; use rocket::http::RawStr; @@ -73,7 +74,7 @@ pub struct Street { /// * `street` - name of the street /// * `city` - city the street is in // TODO find out how to do this async -pub fn search_streets(street_name: &String) -> Result, Box> { +pub fn search_streets(street_name: &String) -> Result, FejError> { let client = reqwest::Client::new(); let response = client.get(SEARCH_URL).query(&[("q", street_name)]).send()?; let data: Vec> = response.json()?; diff --git a/src/ivago/mod.rs b/src/ivago/mod.rs index 33ab64e..c173aab 100644 --- a/src/ivago/mod.rs +++ b/src/ivago/mod.rs @@ -2,6 +2,7 @@ mod controller; #[cfg(test)] mod tests; +use crate::errors::FejError; use rocket::http::Status; use rocket_contrib::json::Json; @@ -12,10 +13,8 @@ pub fn routes() -> Vec { // URL: https://www.ivago.be/nl/particulier/autocomplete/garbage/streets?q=Lange #[get("/search?")] pub fn route_search_streets(street: String) -> Result>, Status> { - match controller::search_streets(&street) { - Ok(streets) => Ok(Json(streets)), - Err(_) => Err(Status::InternalServerError), - } + let result = controller::search_streets(&street)?; + Ok(Json(result)) } #[get("/?&&&")] diff --git a/src/main.rs b/src/main.rs index 8a5ea07..882db7c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,6 +4,7 @@ extern crate rocket; // Route modules +mod errors; mod hello; mod ivago;