this repo has no description
1use axum::http::StatusCode;
2use axum::response::{IntoResponse, Response};
3use serde_json::json;
4
5#[derive(Debug)]
6pub enum AppError {
7 BadRequest(String),
8 Unauthorized(String),
9 NotFound(String),
10 Internal(String),
11}
12
13impl std::fmt::Display for AppError {
14 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
15 match self {
16 AppError::BadRequest(msg) => write!(f, "Bad request: {msg}"),
17 AppError::Unauthorized(msg) => write!(f, "Unauthorized: {msg}"),
18 AppError::NotFound(msg) => write!(f, "Not found: {msg}"),
19 AppError::Internal(msg) => write!(f, "Internal error: {msg}"),
20 }
21 }
22}
23
24impl IntoResponse for AppError {
25 fn into_response(self) -> Response {
26 let (status, message) = match &self {
27 AppError::BadRequest(msg) => (StatusCode::BAD_REQUEST, msg.clone()),
28 AppError::Unauthorized(msg) => (StatusCode::UNAUTHORIZED, msg.clone()),
29 AppError::NotFound(msg) => (StatusCode::NOT_FOUND, msg.clone()),
30 AppError::Internal(msg) => (StatusCode::INTERNAL_SERVER_ERROR, msg.clone()),
31 };
32
33 let body = axum::Json(json!({ "error": message }));
34 (status, body).into_response()
35 }
36}
37
38impl From<sqlx::Error> for AppError {
39 fn from(err: sqlx::Error) -> Self {
40 AppError::Internal(err.to_string())
41 }
42}