mahjong_service/
service_error.rs

1use actix_web::{body::BoxBody, http::StatusCode, HttpResponse, ResponseError};
2use std::fmt::{self, Display};
3
4#[derive(Debug)]
5pub enum ServiceError {
6    GameNotFound,
7    GameVersionMismatch,
8    ErrorLoadingGame,
9    Custom(&'static str),
10}
11
12impl Display for ServiceError {
13    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
14        match self {
15            Self::GameNotFound => write!(f, "Game not found"),
16            Self::GameVersionMismatch => write!(f, "Game version mismatch"),
17            Self::ErrorLoadingGame => write!(f, "Error loading game"),
18            Self::Custom(msg) => write!(f, "{}", msg),
19        }
20    }
21}
22
23impl ResponseError for ServiceError {
24    fn status_code(&self) -> StatusCode {
25        match self {
26            Self::GameNotFound => StatusCode::NOT_FOUND,
27            Self::GameVersionMismatch => StatusCode::BAD_REQUEST,
28            Self::ErrorLoadingGame => StatusCode::INTERNAL_SERVER_ERROR,
29            Self::Custom(_) => StatusCode::INTERNAL_SERVER_ERROR,
30        }
31    }
32
33    fn error_response(&self) -> HttpResponse<BoxBody> {
34        match self {
35            Self::GameNotFound => HttpResponse::NotFound().body("Game not found"),
36            Self::GameVersionMismatch => HttpResponse::BadRequest().body("Game version mismatch"),
37            Self::ErrorLoadingGame => {
38                HttpResponse::InternalServerError().body("Error loading game")
39            }
40            Self::Custom(msg) => HttpResponse::InternalServerError().body(msg.to_string()),
41        }
42    }
43}
44
45pub type ResponseCommon = actix_web::Result<HttpResponse>;