use axum::{
http::StatusCode,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
use std::collections::BTreeMap;
pub type ValidationErrors = BTreeMap<String, Vec<String>>;
pub type Result<T = ()> = std::result::Result<T, AppError>;
#[derive(thiserror::Error)]
pub enum AppError {
#[error("Resource not found")]
NotFound,
#[error("Unauthenticated")]
Unauthorized,
#[error("Forbidden")]
Forbidden,
#[error("Validation failed")]
Validation(ValidationErrors),
#[error("{0}")]
Conflict(String),
#[error("{0}")]
BadRequest(String),
#[error("Request body too large")]
PayloadTooLarge,
#[error("Content-Type must be application/json")]
UnsupportedMediaType,
#[error("Method not allowed")]
MethodNotAllowed,
#[error("Database operation failed")]
Database(#[from] sea_orm::DbErr),
#[error("Failed to connect to database: {}. Check DATABASE_URL and database availability.", connection_cause(.0))]
DatabaseConnection(#[source] sea_orm::DbErr),
#[error("Internal server error")]
Internal(#[from] anyhow::Error),
#[error("{0}")]
Configuration(String),
#[error("Could not start the HTTP server. Check APP_HOST, APP_PORT, and port availability.")]
Io(#[from] std::io::Error),
}
impl std::fmt::Debug for AppError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self, f)
}
}
#[derive(Clone, Copy, Debug)]
pub struct ErrorKind(pub &'static str);
fn connection_cause(error: &sea_orm::DbErr) -> &'static str {
use sea_orm::{ConnAcquireErr, DbErr, RuntimeErr, SqlxError};
match error {
DbErr::ConnectionAcquire(ConnAcquireErr::Timeout) => "connection pool timed out",
DbErr::ConnectionAcquire(ConnAcquireErr::ConnectionClosed) => "connection pool closed",
DbErr::Conn(RuntimeErr::SqlxError(error)) => match error {
SqlxError::Io(e) => match e.kind() {
std::io::ErrorKind::ConnectionRefused => "connection refused",
std::io::ErrorKind::TimedOut => "connection timed out",
std::io::ErrorKind::PermissionDenied => "permission denied",
_ => "network or filesystem I/O failure",
},
SqlxError::Tls(_) => "TLS negotiation failed",
SqlxError::Configuration(_) => "invalid connection options",
SqlxError::Database(_) => "database rejected the connection",
SqlxError::PoolTimedOut => "connection pool timed out",
_ => "driver connection failure",
},
_ => "driver connection failure",
}
}
impl AppError {
pub fn kind(&self) -> &'static str {
match self {
Self::Database(_) | Self::DatabaseConnection(_) => "database",
Self::Internal(_) => "internal",
Self::Configuration(_) => "configuration",
Self::Io(_) => "io",
Self::Validation(_) => "validation",
_ => "request",
}
}
pub fn status(&self) -> StatusCode {
match self {
Self::NotFound => StatusCode::NOT_FOUND,
Self::Unauthorized => StatusCode::UNAUTHORIZED,
Self::Forbidden => StatusCode::FORBIDDEN,
Self::Validation(_) => StatusCode::UNPROCESSABLE_ENTITY,
Self::Conflict(_) => StatusCode::CONFLICT,
Self::BadRequest(_) => StatusCode::BAD_REQUEST,
Self::PayloadTooLarge => StatusCode::PAYLOAD_TOO_LARGE,
Self::UnsupportedMediaType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
Self::MethodNotAllowed => StatusCode::METHOD_NOT_ALLOWED,
_ => StatusCode::INTERNAL_SERVER_ERROR,
}
}
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let status = self.status();
let body = if let Self::Validation(errors) = &self {
json!({ "message": "Validation failed", "errors": errors })
} else if status.is_server_error() {
json!({ "message": "Internal server error" })
} else {
json!({ "message": self.to_string() })
};
let mut response = (status, Json(body)).into_response();
response.extensions_mut().insert(ErrorKind(self.kind()));
response
}
}