diff --git a/src/data/error.rs b/src/data/error.rs index 65fb93c..0974f49 100644 --- a/src/data/error.rs +++ b/src/data/error.rs @@ -1,6 +1,7 @@ use core::fmt; use serde::export::Formatter; use std::error; +use std::error::Error; /// Simple rust error /// @@ -9,6 +10,7 @@ use std::error; /// Simple result type pub type ResultExecError = Result; +pub type ResultBoxError = Result>; #[derive(Debug, Clone)] pub struct ExecError(pub String); diff --git a/src/data/http_error.rs b/src/data/http_error.rs index 5f5cb57..81deede 100644 --- a/src/data/http_error.rs +++ b/src/data/http_error.rs @@ -27,4 +27,12 @@ impl HttpError { message: message.to_string() } } + + /// Generate a 401 error + pub fn bad_request(message: &str) -> HttpError { + HttpError { + code: 401, + message: message.to_string() + } + } } \ No newline at end of file diff --git a/src/data/http_request_handler.rs b/src/data/http_request_handler.rs index a2d93ab..646f685 100644 --- a/src/data/http_request_handler.rs +++ b/src/data/http_request_handler.rs @@ -4,7 +4,7 @@ use crate::data::http_error::HttpError; use std::convert::TryFrom; use std::error::Error; use serde::Serialize; -use crate::data::error::{ResultExecError, ExecError}; +use crate::data::error::{ResultBoxError}; use std::collections::HashMap; /// Http request handler @@ -76,14 +76,20 @@ impl HttpRequestHandler { Err(Box::try_from(actix_web::error::ErrorInternalServerError(error)).unwrap()) } + /// Bad request + pub fn bad_request(&mut self, message: String) -> RequestResult { + self.response = Some(HttpResponse::BadRequest().json( + HttpError::bad_request(&message))); + Err(Box::try_from(actix_web::error::ErrorBadRequest(message)).unwrap()) + } + /// Get the path of the request pub fn request_path(&self) -> String { self.request.path().to_string() } /// Check login tokens - pub fn check_client_token(&mut self) -> ResultExecError<()> { - + pub fn check_client_token(&mut self) -> Result<(), Box> { println!("me = {}", self.post_string("me")?); Ok(()) @@ -95,17 +101,20 @@ impl HttpRequestHandler { } /// Get a post parameter - pub fn post_parameter(&self, name: &str) -> Result<&RequestValue, ExecError> { - self.body.get(name) - .ok_or(ExecError(format!("POST parameter {} not found in request!", name))) + pub fn post_parameter(&mut self, name: &str) -> ResultBoxError<&RequestValue> { + if !self.has_post_parameter(name) { + self.bad_request(format!("POST parameter '{}' not found in request!", name))?; + } + + Ok(self.body.get(name).unwrap()) } /// Get a post string - pub fn post_string(&self, name: &str) -> Result { + pub fn post_string(&mut self, name: &str) -> Result> { let param = self.post_parameter(name)?; match ¶m.string { - None => Err(ExecError(format!("{} is not a string!", name))), + None => Err(Box::new(actix_web::error::ErrorBadRequest(format!("{} is not a string!", name)))), Some(s) => Ok(s.to_string()) } }