use axum::{
http::StatusCode,
response::{IntoResponse, Response},
Json,
};
use serde::Serialize;
use std::collections::BTreeMap;
pub type ValidationErrors = BTreeMap<String, Vec<String>>;
#[derive(Clone, Debug, Serialize, schemars::JsonSchema)]
pub struct ApiErrorResponse {
#[serde(skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
#[schemars(with = "ValidationErrors")]
pub errors: Option<ValidationErrors>,
}
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("Too many requests; try again later")]
TooManyRequests,
#[error("Service temporarily unavailable")]
AuthCapacity,
#[error("Service temporarily unavailable")]
ClientIdentityUnavailable,
#[error("Internal server error")]
Lifecycle,
#[error("{0}")]
Rejected(#[from] crate::EventRejection),
#[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 from_json_rejection(error: axum::extract::rejection::JsonRejection) -> Self {
match error.status() {
StatusCode::PAYLOAD_TOO_LARGE => Self::PayloadTooLarge,
StatusCode::UNSUPPORTED_MEDIA_TYPE => Self::UnsupportedMediaType,
StatusCode::UNPROCESSABLE_ENTITY => Self::Validation(
[(
"body".into(),
vec!["The JSON body has missing or invalid fields.".into()],
)]
.into(),
),
_ => Self::BadRequest("Malformed JSON body".into()),
}
}
pub fn kind(&self) -> &'static str {
match self {
Self::Lifecycle => "lifecycle",
Self::Rejected(_) => "application_rejection",
Self::AuthCapacity => "auth_capacity",
Self::ClientIdentityUnavailable => "client_identity",
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::Rejected(problem) => problem.status(),
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,
Self::TooManyRequests => StatusCode::TOO_MANY_REQUESTS,
Self::AuthCapacity | Self::ClientIdentityUnavailable => StatusCode::SERVICE_UNAVAILABLE,
_ => StatusCode::INTERNAL_SERVER_ERROR,
}
}
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let status = self.status();
let body = if let Self::Rejected(problem) = &self {
ApiErrorResponse {
code: Some(problem.code().into()),
message: problem.to_string(),
errors: match problem {
crate::EventRejection::Validation { errors, .. } => Some(errors.clone()),
_ => None,
},
}
} else if let Self::Validation(errors) = &self {
ApiErrorResponse {
code: None,
message: "Validation failed".into(),
errors: Some(errors.clone()),
}
} else if status.is_server_error() {
ApiErrorResponse {
code: None,
message: if status == StatusCode::SERVICE_UNAVAILABLE {
"Service temporarily unavailable"
} else {
"Internal server error"
}
.into(),
errors: None,
}
} else {
ApiErrorResponse {
code: None,
message: self.to_string(),
errors: None,
}
};
let mut response = (status, Json(body)).into_response();
response.extensions_mut().insert(ErrorKind(self.kind()));
response
}
}