ferrik-core 0.0.2

Core runtime, triple-response engine, AI discovery, and testing framework for Ferrik
Documentation
//! Unified error handling across HTML, JSON, and AI Markdown responses.

use axum::http::{header, StatusCode};
use axum::response::{IntoResponse, Response};
use serde::Serialize;
use thiserror::Error;

use crate::response::ResponseFormat;

/// Core application error type returned by Ferrik controllers and services.
#[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>>,
}

impl AppError {
    /// Returns the HTTP status code associated with this error variant.
    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,
        }
    }

    /// Returns validation details if this is a validation error.
    pub fn details(&self) -> Option<Vec<String>> {
        match self {
            AppError::Validation(errs) => Some(errs.clone()),
            _ => None,
        }
    }

    /// Wraps this error with a target response format so it renders appropriately.
    pub fn with_format(self, format: ResponseFormat) -> FormattedError {
        FormattedError {
            format,
            error: self,
        }
    }

    /// Renders this error into an HTTP response for the given format.
    pub fn into_format_response(self, format: ResponseFormat) -> Response {
        let status = self.status_code();
        let message = self.to_string();
        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 IntoResponse for AppError {
    fn into_response(self) -> Response {
        self.into_format_response(ResponseFormat::Json)
    }
}

/// An `AppError` bound to a specific [`ResponseFormat`] for format-aware rendering.
#[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('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}

#[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("&lt;script&gt;"));

        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);
    }
}