actix_web_utils/traits/
macro_traits.rs

1use std::fmt::Display;
2use serde::Serialize;
3
4use crate::{dtos::message::MessageResource, enums::error::Error, extensions::{typed_response::TypedHttpResponse, generic_error::GenericError}};
5
6/// This trait aims to aid macros defined in this crate so that the macro can take any shape of error and
7/// do the same thing for all.
8pub trait ReturnableErrorShape {
9    fn convert_to_returnable<T: Serialize> (&self, status_code: u16) -> TypedHttpResponse<T>;
10}
11impl ReturnableErrorShape for MessageResource {
12    fn convert_to_returnable<T: Serialize>(&self, status_code: u16) -> TypedHttpResponse<T> {
13        TypedHttpResponse::return_standard_error(status_code, self.clone())
14    }
15}
16impl ReturnableErrorShape for Error {
17    fn convert_to_returnable<T: Serialize>(&self, status_code: u16) -> TypedHttpResponse<T> {
18        //debug!("Converted error to returnable. Error: {}", self.to_string());
19        match self {
20            Error::Unspecified => TypedHttpResponse::return_standard_error(status_code, MessageResource::new_empty()),
21            Error::NetworkError(message) => TypedHttpResponse::return_standard_error(status_code, message.clone()),
22            Error::UnexpectedStatusCode(_, actual, messages) => TypedHttpResponse::return_standard_error_list(*actual, messages.clone()),
23            Error::ClientError(message) => TypedHttpResponse::return_standard_error(status_code, message.clone()),
24            Error::SerdeError(message, _) => TypedHttpResponse::return_standard_error(status_code, message.clone()),
25            Error::DatabaseError(message, _) => TypedHttpResponse::return_standard_error(status_code, message.clone()),
26            Error::ComputeError(message) => TypedHttpResponse::return_standard_error(status_code, message.clone()),
27        }
28    }
29}
30impl ReturnableErrorShape for Vec<MessageResource> {
31    fn convert_to_returnable<T: Serialize>(&self, status_code: u16) -> TypedHttpResponse<T> {
32        TypedHttpResponse::return_standard_error_list(status_code, self.to_vec())
33    }
34}
35impl<E: Display> ReturnableErrorShape for GenericError<E>{
36    fn convert_to_returnable<T: Serialize>(&self, status_code: u16) -> TypedHttpResponse<T> {
37        TypedHttpResponse::return_standard_error(status_code, MessageResource::new_from_str(&self.error.to_string()))
38    }
39}