use actix_web::{ error::BlockingError, http::{header::ContentType, StatusCode}, HttpResponse, ResponseError, }; use serde::{Deserialize, Serialize}; use std::fmt::{Display, Formatter, Result}; use validator::ValidationErrors; use gamenight_database::error::DatabaseError; #[derive(Serialize, Deserialize, Debug)] pub struct ApiError { #[serde(skip_serializing)] pub status: u16, pub message: String, } impl Display for ApiError { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, "{}", self.message) } } impl ResponseError for ApiError { fn error_response(&self) -> HttpResponse { HttpResponse::build(StatusCode::from_u16(self.status).unwrap()) .content_type(ContentType::json()) .body(serde_json::to_string(&self).unwrap()) } } impl From for ApiError { fn from(value: DatabaseError) -> Self { ApiError { status: 500, message: value.0, } } } impl From for ApiError { fn from(value: BlockingError) -> Self { ApiError { status: 500, message: value.to_string(), } } } impl From for ApiError { fn from(value: serde_json::Error) -> Self { ApiError { status: 500, message: value.to_string(), } } } impl From for ApiError { fn from(value: jsonwebtoken::errors::Error) -> Self { ApiError { status: 500, message: value.to_string(), } } } impl From for ApiError { fn from(value: ValidationErrors) -> Self { ApiError { status: 422, message: value.to_string(), } } } impl From for ApiError { fn from(value: chrono::ParseError) -> Self { ApiError { status: 422, message: value.to_string(), } } } impl From for ApiError { fn from(value: uuid::Error) -> Self { ApiError { status: 422, message: value.to_string(), } } }