use axum::extract::Request;
use axum::http::{header, StatusCode};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use serde::Serialize;
use thiserror::Error;
use crate::response::{Format, ResponseFormat};
#[derive(Debug, Error)]
pub enum AppError {
#[error("Resource not found: {0}")]
NotFound(String),
#[error("Validation failed")]
Validation(Vec<String>),
#[error("Unauthorized: {0}")]
Unauthorized(String),
#[error("Forbidden: {0}")]
Forbidden(String),
#[error("Bad request: {0}")]
BadRequest(String),
#[error("Database error: {0}")]
Database(#[from] sea_orm::DbErr),
#[error("Template rendering error: {0}")]
Template(#[from] askama::Error),
#[error("Configuration error: {0}")]
Config(String),
#[error("Internal server error: {0}")]
Internal(String),
}
#[derive(Debug, Serialize)]
struct JsonErrorPayload {
status: String,
code: u16,
message: String,
#[serde(skip_serializing_if = "Option::is_none")]
errors: Option<Vec<String>>,
}
#[derive(Debug, Clone)]
struct PublicErrorInfo {
status: StatusCode,
message: String,
details: Option<Vec<String>>,
}
impl PublicErrorInfo {
fn into_format_response(self, format: ResponseFormat) -> Response {
let status = self.status;
let message = self.message;
let details = self.details;
match format {
ResponseFormat::Json => {
let payload = JsonErrorPayload {
status: "error".to_string(),
code: status.as_u16(),
message,
errors: details,
};
let body = serde_json::to_string(&payload)
.unwrap_or_else(|_| r#"{"status":"error","code":500,"message":"Serialization error"}"#.to_string());
(
status,
[(header::CONTENT_TYPE, "application/json; charset=utf-8")],
body,
)
.into_response()
}
ResponseFormat::Ai => {
let mut md = format!(
"---\nstatus: error\ncode: {}\nmessage: {:?}\n---\n\n# Error {}\n\n{}\n",
status.as_u16(),
message,
status.as_u16(),
message
);
if let Some(errs) = details {
md.push_str("\n## Validation Errors\n\n");
for err in errs {
md.push_str(&format!("- {}\n", err));
}
}
(
status,
[(header::CONTENT_TYPE, "text/markdown; charset=utf-8")],
md,
)
.into_response()
}
ResponseFormat::Html => {
let mut list_html = String::new();
if let Some(errs) = details {
list_html.push_str("<ul>");
for err in errs {
list_html.push_str(&format!("<li>{}</li>", escape_html(&err)));
}
list_html.push_str("</ul>");
}
let html = format!(
"<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>Error {code}</title></head><body><main><h1>Error {code}</h1><p>{msg}</p>{list}</main></body></html>",
code = status.as_u16(),
msg = escape_html(&message),
list = list_html
);
(
status,
[(header::CONTENT_TYPE, "text/html; charset=utf-8")],
html,
)
.into_response()
}
}
}
}
impl AppError {
pub fn status_code(&self) -> StatusCode {
match self {
AppError::NotFound(_) => StatusCode::NOT_FOUND,
AppError::Validation(_) => StatusCode::UNPROCESSABLE_ENTITY,
AppError::Unauthorized(_) => StatusCode::UNAUTHORIZED,
AppError::Forbidden(_) => StatusCode::FORBIDDEN,
AppError::BadRequest(_) => StatusCode::BAD_REQUEST,
AppError::Database(_)
| AppError::Template(_)
| AppError::Config(_)
| AppError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
}
}
pub fn public_message(&self) -> String {
match self {
AppError::NotFound(_)
| AppError::Validation(_)
| AppError::Unauthorized(_)
| AppError::Forbidden(_)
| AppError::BadRequest(_) => self.to_string(),
AppError::Database(_)
| AppError::Template(_)
| AppError::Config(_)
| AppError::Internal(_) => {
tracing::error!(error = %self, "Internal server error");
"Internal server error".to_string()
}
}
}
pub fn details(&self) -> Option<Vec<String>> {
match self {
AppError::Validation(errs) => Some(errs.clone()),
_ => None,
}
}
pub fn with_format(self, format: ResponseFormat) -> FormattedError {
FormattedError {
format,
error: self,
}
}
pub fn into_format_response(self, format: ResponseFormat) -> Response {
let info = PublicErrorInfo {
status: self.status_code(),
message: self.public_message(),
details: self.details(),
};
info.into_format_response(format)
}
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let info = PublicErrorInfo {
status: self.status_code(),
message: self.public_message(),
details: self.details(),
};
let mut resp = info.clone().into_format_response(ResponseFormat::Json);
resp.extensions_mut().insert(info);
resp
}
}
pub async fn format_errors_middleware(req: Request, next: Next) -> Response {
let format = Format::negotiate(req.uri().path(), req.headers());
let resp = next.run(req).await;
if format != ResponseFormat::Json {
if let Some(info) = resp.extensions().get::<PublicErrorInfo>().cloned() {
return info.into_format_response(format);
}
}
resp
}
#[derive(Debug)]
pub struct FormattedError {
pub format: ResponseFormat,
pub error: AppError,
}
impl IntoResponse for FormattedError {
fn into_response(self) -> Response {
self.error.into_format_response(self.format)
}
}
fn escape_html(input: &str) -> String {
input
.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
}
#[cfg(test)]
mod tests {
use super::*;
use http_body_util::BodyExt;
async fn body_to_string(resp: Response) -> String {
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
String::from_utf8(bytes.to_vec()).unwrap()
}
#[tokio::test]
async fn error_status_codes_match_variants() {
assert_eq!(AppError::NotFound("x".into()).status_code(), StatusCode::NOT_FOUND);
assert_eq!(
AppError::Validation(vec!["bad".into()]).status_code(),
StatusCode::UNPROCESSABLE_ENTITY
);
assert_eq!(
AppError::Unauthorized("no".into()).status_code(),
StatusCode::UNAUTHORIZED
);
assert_eq!(AppError::Forbidden("no".into()).status_code(), StatusCode::FORBIDDEN);
assert_eq!(AppError::BadRequest("no".into()).status_code(), StatusCode::BAD_REQUEST);
assert_eq!(
AppError::Config("bad".into()).status_code(),
StatusCode::INTERNAL_SERVER_ERROR
);
assert_eq!(
AppError::Internal("boom".into()).status_code(),
StatusCode::INTERNAL_SERVER_ERROR
);
}
#[tokio::test]
async fn error_renders_json_html_and_ai() {
let resp = AppError::Validation(vec!["title cannot be blank".into()])
.with_format(ResponseFormat::Json)
.into_response();
assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
let body = body_to_string(resp).await;
assert!(body.contains("title cannot be blank"));
let resp = AppError::Validation(vec!["<script>".into()])
.with_format(ResponseFormat::Html)
.into_response();
assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
let body = body_to_string(resp).await;
assert!(body.contains("<script>"));
let resp = AppError::Validation(vec!["invalid email".into()])
.with_format(ResponseFormat::Ai)
.into_response();
assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
let body = body_to_string(resp).await;
assert!(body.contains("status: error"));
assert!(body.contains("- invalid email"));
let default_resp = AppError::NotFound("post 1".into()).into_response();
assert_eq!(default_resp.status(), StatusCode::NOT_FOUND);
}
}