57 lines
1.7 KiB
Rust
57 lines
1.7 KiB
Rust
use axum::{
|
|
Json,
|
|
http::StatusCode,
|
|
response::{IntoResponse, Response},
|
|
};
|
|
use serde_json::json;
|
|
use thiserror::Error;
|
|
|
|
#[derive(Error, Debug)]
|
|
pub enum AppError {
|
|
#[error("Database error: {0}")]
|
|
Database(#[from] sea_orm::DbErr),
|
|
|
|
#[error("Configuration error: {0}")]
|
|
Config(String),
|
|
|
|
#[error("Not found: {0}")]
|
|
NotFound(String),
|
|
|
|
#[error("Unauthorized: {0}")]
|
|
Unauthorized(String),
|
|
|
|
#[error("Internal server error: {0}")]
|
|
Internal(String),
|
|
|
|
#[error("Network error: {0}")]
|
|
Network(#[from] reqwest::Error),
|
|
|
|
#[error("Invalid request: {0}")]
|
|
InvalidRequest(String),
|
|
}
|
|
|
|
impl IntoResponse for AppError {
|
|
fn into_response(self) -> Response {
|
|
let (status, error_message) = match &self {
|
|
AppError::Database(err) => (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()),
|
|
AppError::Config(err) => (StatusCode::INTERNAL_SERVER_ERROR, err.clone()),
|
|
AppError::NotFound(err) => (StatusCode::NOT_FOUND, err.clone()),
|
|
AppError::Unauthorized(err) => (StatusCode::UNAUTHORIZED, err.clone()),
|
|
AppError::Internal(err) => (StatusCode::INTERNAL_SERVER_ERROR, err.clone()),
|
|
AppError::Network(err) => (StatusCode::BAD_GATEWAY, err.to_string()),
|
|
AppError::InvalidRequest(err) => (StatusCode::BAD_REQUEST, err.clone()),
|
|
};
|
|
|
|
if status.is_server_error() || status.is_client_error() {
|
|
tracing::error!(%status, error = %self, "AppError converted to response");
|
|
}
|
|
|
|
let body = Json(json!({
|
|
"error": error_message,
|
|
}));
|
|
|
|
(status, body).into_response()
|
|
}
|
|
}
|
|
|
|
pub type AppResult<T> = Result<T, AppError>;
|