Skip to main content

norm_spec/
error.rs

1use std::{error::Error, fmt};
2
3use norm_spec_core::ErrorDetail;
4
5/// Stable caller-facing classification for a high-level API failure.
6#[derive(Clone, Copy, Debug, Eq, PartialEq)]
7pub enum FailureClass {
8    /// The request is invalid or names unavailable configuration.
9    Usage,
10    /// Filesystem or input processing prevented the requested operation.
11    Operation,
12}
13
14/// A handled high-level API failure with stable machine-readable detail.
15#[derive(Clone, Debug, Eq, PartialEq)]
16pub struct ApiError {
17    class: FailureClass,
18    detail: ErrorDetail,
19}
20
21impl ApiError {
22    pub(crate) fn usage(detail: ErrorDetail) -> Self {
23        Self {
24            class: FailureClass::Usage,
25            detail,
26        }
27    }
28
29    pub(crate) fn operation(detail: ErrorDetail) -> Self {
30        Self {
31            class: FailureClass::Operation,
32            detail,
33        }
34    }
35
36    /// Return whether the caller or the attempted operation caused the failure.
37    #[must_use]
38    pub const fn class(&self) -> FailureClass {
39        self.class
40    }
41
42    /// Return the stable error code, message, and optional path or field.
43    #[must_use]
44    pub const fn detail(&self) -> &ErrorDetail {
45        &self.detail
46    }
47
48    /// Consume the error and return its stable machine-readable detail.
49    #[must_use]
50    pub fn into_detail(self) -> ErrorDetail {
51        self.detail
52    }
53}
54
55impl fmt::Display for ApiError {
56    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
57        write!(formatter, "{}: {}", self.detail.code, self.detail.message)
58    }
59}
60
61impl Error for ApiError {}