[#9] Added general error module

master
Jef Roosens 2021-04-04 13:03:08 +02:00
parent a80774b341
commit eab31e5e91
Signed by: Jef Roosens
GPG Key ID: B580B976584B5F30
4 changed files with 29 additions and 5 deletions

23
src/errors.rs 100644
View File

@ -0,0 +1,23 @@
use reqwest::Error;
use rocket::http::Status;
pub enum FejError {
InvalidArgument,
FailedRequest,
}
impl From<FejError> 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<Error> for FejError {
fn from(_: Error) -> FejError {
FejError::FailedRequest
}
}

View File

@ -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<Vec<Street>, Box<dyn Error>> {
pub fn search_streets(street_name: &String) -> Result<Vec<Street>, FejError> {
let client = reqwest::Client::new();
let response = client.get(SEARCH_URL).query(&[("q", street_name)]).send()?;
let data: Vec<HashMap<String, String>> = response.json()?;

View File

@ -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<rocket::Route> {
// URL: https://www.ivago.be/nl/particulier/autocomplete/garbage/streets?q=Lange
#[get("/search?<street>")]
pub fn route_search_streets(street: String) -> Result<Json<Vec<controller::Street>>, 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("/?<street>&<number>&<start_date>&<end_date>")]

View File

@ -4,6 +4,7 @@
extern crate rocket;
// Route modules
mod errors;
mod hello;
mod ivago;