yao_dev_common/error/
app_error.rs

1use crate::error::repo_error::RepoError;
2use anyhow::Error;
3use axum::http::StatusCode;
4use axum::response::{IntoResponse, Response};
5use axum::Json;
6use serde_json::json;
7
8#[derive(Debug, thiserror::Error)]
9pub enum AppError {
10    #[allow(dead_code)]
11    #[error("Unauthorized: {0}")]
12    Unauthorized(String), // 401
13
14    #[allow(dead_code)]
15    #[error("Invalid params: {0:?}")]
16    InvalidParams(Vec<&'static str>), // 400
17
18    #[allow(dead_code)]
19    #[error("Error parsing `multipart/form-data` request.\n{0}")]
20    MultipartError(String), // 400
21
22    #[allow(dead_code)]
23    #[error("Not Found: {0}")]
24    NotFound(&'static str), // 404
25
26    #[allow(dead_code)]
27    #[error("Internal Server Error: {0}")]
28    InternalServerError(#[from] anyhow::Error), // 500
29
30    #[allow(dead_code)]
31    #[error("Json parse Error: {0}")]
32    JsonError(#[from] serde_json::Error),
33
34    #[allow(dead_code)]
35    #[error("Reqwest Error: {0}")]
36    ReqwestError(#[from] reqwest::Error),
37
38    #[allow(dead_code)]
39    #[error("Askama Error: {0}")]
40    AskamaError(#[from] askama::Error),
41
42    #[allow(dead_code)]
43    #[error("Custom Error: {0}")]
44    CustomError(String), // 500
45}
46
47impl IntoResponse for AppError {
48    fn into_response(self) -> Response {
49        let (status, error_message) = match self {
50            AppError::Unauthorized(_) => (StatusCode::UNAUTHORIZED, self.to_string()), // 401
51            AppError::InvalidParams(_) => (StatusCode::BAD_REQUEST, self.to_string()), // 400
52            AppError::MultipartError(_) => (StatusCode::BAD_REQUEST, self.to_string()), // 400
53            AppError::NotFound(_) => (StatusCode::NOT_FOUND, self.to_string()),        // 404
54            AppError::JsonError(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()), // 500
55            AppError::ReqwestError(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()), // 500
56            AppError::AskamaError(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()), // 500
57            AppError::InternalServerError(_) => {
58                (StatusCode::INTERNAL_SERVER_ERROR, self.to_string())
59            } // 500
60            AppError::CustomError(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()), // 500
61        };
62        let body = Json(json!({"error": error_message}));
63        (status, body).into_response()
64    }
65}
66
67impl From<RepoError> for AppError {
68    fn from(error: RepoError) -> Self {
69        AppError::InternalServerError(Error::from(error))
70    }
71}
72
73impl From<&str> for AppError {
74    fn from(msg: &str) -> Self {
75        AppError::CustomError(msg.to_string())
76    }
77}
78
79impl From<String> for AppError {
80    fn from(msg: String) -> Self {
81        AppError::CustomError(msg)
82    }
83}