1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
use std::error::Error; use std::fmt::{Display, Formatter}; use serde::{Serialize, Deserialize}; use rocket::response::Responder; use rocket::{Request, Response}; use rocket::http::Status; use crate::database::responders::CommonResponders; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct RpaError { pub description: String, pub cause: String } impl RpaError { pub fn map_result<T>(error_message: String, result: Result<T, diesel::result::Error>) -> Result<T, RpaError> { if result.is_err() { let result_error = result.err().unwrap(); return RpaError::build_from(error_message, result_error); } Ok(result.unwrap()) } pub fn builder() -> RpaErrorBuilder { RpaErrorBuilder{ instance: RpaError{ description: "".to_string(), cause: "".to_string() } } } pub fn build_from<T>(error_message: String, cause: diesel::result::Error) -> Result<T, RpaError> { RpaError::builder().with_description(error_message.as_str()).with_cause(cause).result::<T>() } } pub struct RpaErrorBuilder { pub instance: RpaError } impl RpaErrorBuilder { pub fn with_description(mut self, description: &str) -> RpaErrorBuilder { self.instance.description = description.to_string(); self } pub fn with_cause(mut self, cause: diesel::result::Error) -> RpaErrorBuilder { self.instance.cause = cause.to_string(); self } pub fn build(self) -> RpaError { self.instance } pub fn result<T>(self) -> Result<T, RpaError> { Err(self.instance) } } impl Error for RpaError { fn description(&self) -> &str { self.description.as_str() } } impl Display for RpaError { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { write!(f, "{}", self.description) } } impl Responder<'static> for RpaError { fn respond_to(self, request: &Request) -> Result<Response<'static>, Status> { CommonResponders::json_responder(self, request) } }