footing 0.1.19

Feature-gated foundations for Rust backend services
Documentation
use crate::result::{ClassifyError, ErrorBoundaryDecision, ErrorBoundaryPolicy};

use super::{ApiProblem, IntoApiProblem, PublicError};
use crate::http::request_context::RequestContext;

#[derive(Debug, Clone, Copy)]
/// Represents API error boundary.
pub struct ApiErrorBoundary {
    policy: ErrorBoundaryPolicy,
}

impl ApiErrorBoundary {
    #[must_use]
    /// Creates a new instance.
    pub const fn new(policy: ErrorBoundaryPolicy) -> Self {
        Self { policy }
    }

    #[must_use]
    /// Creates HTTP API.
    pub const fn http_api() -> Self {
        Self::new(ErrorBoundaryPolicy::http_api())
    }

    #[must_use]
    /// Returns the policy.
    pub const fn policy(&self) -> ErrorBoundaryPolicy {
        self.policy
    }

    #[must_use]
    /// Determines the value.
    pub fn decide<E>(&self, error: &E) -> ErrorBoundaryDecision
    where
        E: ClassifyError + ?Sized,
    {
        self.policy.decide(error)
    }

    #[must_use]
    /// Returns the problem.
    pub fn problem<E>(&self, error: &E, context: &RequestContext) -> ApiProblem
    where
        E: ClassifyError + ?Sized,
    {
        self.problem_from_decision(self.decide(error), context)
    }

    #[must_use]
    /// Returns the problem from decision.
    pub fn problem_from_decision(
        &self,
        decision: ErrorBoundaryDecision,
        context: &RequestContext,
    ) -> ApiProblem {
        PublicError::from_descriptor(decision.into_descriptor())
            .into_api_problem()
            .with_request_context(context)
    }
}