rpa_macros/database/
error.rsuse 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)
}
}