yao_dev_common/error/
app_error.rs1use 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), #[allow(dead_code)]
15 #[error("Invalid params: {0:?}")]
16 InvalidParams(Vec<&'static str>), #[allow(dead_code)]
19 #[error("Error parsing `multipart/form-data` request.\n{0}")]
20 MultipartError(String), #[allow(dead_code)]
23 #[error("Not Found: {0}")]
24 NotFound(&'static str), #[allow(dead_code)]
27 #[error("Internal Server Error: {0}")]
28 InternalServerError(#[from] anyhow::Error), #[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), }
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()), AppError::InvalidParams(_) => (StatusCode::BAD_REQUEST, self.to_string()), AppError::MultipartError(_) => (StatusCode::BAD_REQUEST, self.to_string()), AppError::NotFound(_) => (StatusCode::NOT_FOUND, self.to_string()), AppError::JsonError(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()), AppError::ReqwestError(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()), AppError::AskamaError(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()), AppError::InternalServerError(_) => {
58 (StatusCode::INTERNAL_SERVER_ERROR, self.to_string())
59 } AppError::CustomError(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()), };
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}