glacier-web 0.4.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! The error type shared across Glacier.

use std::fmt;

use http::StatusCode;

use crate::response::{IntoResponse, Response};

/// `-> Result` in a handler means `-> Result<Response>`.
pub type Result<T = Response, E = Error> = std::result::Result<T, E>;

type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;

/// An error carrying the HTTP status it should be rendered with.
///
/// Any `std::error::Error` converts into a `500 Internal Server Error` via `?`,
/// so handlers can bubble failures up without ceremony. Use the constructors
/// (`Error::not_found()`, `Error::bad_request(..)`, ...) for client errors.
///
/// Like `anyhow::Error`, this type deliberately does not implement
/// `std::error::Error` itself; that is what makes the blanket `From` possible.
pub struct Error {
    status: StatusCode,
    message: String,
    source: Option<BoxError>,
}

impl Error {
    pub fn new(status: StatusCode, message: impl Into<String>) -> Self {
        Self {
            status,
            message: message.into(),
            source: None,
        }
    }

    /// An error with `source` as its cause, kept for
    /// [`downcast_ref`](Self::downcast_ref) and the logs.
    pub fn with_source(
        status: StatusCode,
        message: impl Into<String>,
        source: impl std::error::Error + Send + Sync + 'static,
    ) -> Self {
        Self {
            status,
            message: message.into(),
            source: Some(Box::new(source)),
        }
    }

    /// The cause, if it's an `E`: `err.downcast_ref::<ClientError>()`
    /// says why a call to another service failed.
    pub fn downcast_ref<E: std::error::Error + 'static>(&self) -> Option<&E> {
        self.source.as_deref()?.downcast_ref::<E>()
    }

    pub fn not_found() -> Self {
        Self::new(StatusCode::NOT_FOUND, "Not Found")
    }

    /// `403 Forbidden`: signed in, but not allowed to do this.
    pub fn forbidden() -> Self {
        Self::new(StatusCode::FORBIDDEN, "Forbidden")
    }

    pub fn bad_request(message: impl Into<String>) -> Self {
        Self::new(StatusCode::BAD_REQUEST, message)
    }

    pub fn unprocessable(message: impl Into<String>) -> Self {
        Self::new(StatusCode::UNPROCESSABLE_ENTITY, message)
    }

    pub fn internal(message: impl Into<String>) -> Self {
        Self::new(StatusCode::INTERNAL_SERVER_ERROR, message)
    }

    pub fn status(&self) -> StatusCode {
        self.status
    }

    pub fn message(&self) -> &str {
        &self.message
    }

    /// The underlying error, if this was converted from one.
    pub fn source(&self) -> Option<&(dyn std::error::Error + Send + Sync + 'static)> {
        self.source.as_deref()
    }
}

impl<E> From<E> for Error
where
    E: std::error::Error + Send + Sync + 'static,
{
    fn from(err: E) -> Self {
        Self {
            status: StatusCode::INTERNAL_SERVER_ERROR,
            message: err.to_string(),
            source: Some(Box::new(err)),
        }
    }
}

/// Readable when `main` returns an error; `{:#?}` shows the raw fields.
impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            return f
                .debug_struct("Error")
                .field("status", &self.status)
                .field("message", &self.message)
                .field("source", &self.source)
                .finish();
        }
        write!(f, "{}", self.message)?;
        let mut source = self.source.as_deref().and_then(|err| err.source());
        if source.is_some() {
            write!(f, "\n\nCaused by:")?;
        }
        while let Some(err) = source {
            write!(f, "\n    {err}")?;
            source = err.source();
        }
        Ok(())
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.status, self.message)
    }
}

/// Details of a server error, attached to the response's extensions so the
/// development error page can show them. Never sent to clients as-is.
#[derive(Debug, Clone)]
pub struct ErrorReport {
    pub status: StatusCode,
    pub message: String,
    /// `source()` chain of the underlying error, outermost first.
    pub causes: Vec<String>,
}

/// Marks an error response with no body of its own, just its status line
/// (`Not Found`), so the app can answer it in the format the request asked
/// for, as Rails' public exceptions do. A body the app shaped itself, such
/// as [`JsonErrors`](crate::middleware::JsonErrors)', has no mark.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Bare;

impl IntoResponse for Error {
    fn into_response(self) -> Response {
        if self.status.is_server_error() {
            let mut causes = Vec::new();
            let mut source = self.source.as_deref().and_then(|err| err.source());
            while let Some(err) = source {
                causes.push(err.to_string());
                source = err.source();
            }
            // Never leak internal details to the client; log them instead,
            // inside the request's span.
            tracing::event!(
                target: "glacier",
                tracing::Level::ERROR,
                http.response.status_code = i64::from(self.status.as_u16()),
                error.message = %self.message,
                error.causes = ?causes,
                "request failed: {}",
                self.message
            );
            let reason = self.status.canonical_reason().unwrap_or("Error");
            let mut res = Response::text(reason).with_status(self.status);
            res.extensions_mut().insert(Bare);
            res.extensions_mut().insert(ErrorReport {
                status: self.status,
                message: self.message,
                causes,
            });
            res
        } else {
            let bare = Some(self.message.as_str()) == self.status.canonical_reason();
            let mut res = Response::text(self.message).with_status(self.status);
            if bare {
                res.extensions_mut().insert(Bare);
            }
            res
        }
    }
}