mti/
errors.rs

1//! Error types for the `MagicTypeId` crate.
2//!
3//! This module defines the error types that can occur when working with `MagicTypeIds`.
4//! It includes errors related to both the prefix and suffix components of a `MagicTypeId`.
5
6use std::fmt;
7
8use typeid_prefix::prelude::*;
9use typeid_suffix::prelude::*;
10
11#[cfg(feature = "instrument")]
12use tracing::{error, instrument};
13
14/// Represents errors that can occur when working with `MagicTypeIds`.
15///
16/// This enum encapsulates errors from both the prefix and suffix components
17/// of a `MagicTypeId`, allowing for more specific error handling.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum MagicTypeIdError {
20    /// Errors related to the `TypeID` prefix.
21    ///
22    /// These errors occur when there's an issue with the prefix part of a `MagicTypeId`,
23    /// such as invalid characters or length.
24    Prefix(ValidationError),
25
26    /// Errors related to the `TypeID` suffix.
27    ///
28    /// These errors occur when there's an issue with the suffix part of a `MagicTypeId`,
29    /// such as invalid encoding or an incorrect UUID format.
30    Suffix(DecodeError),
31}
32
33impl fmt::Display for MagicTypeIdError {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        match self {
36            Self::Prefix(err) => write!(f, "Prefix error: {err}"),
37            Self::Suffix(err) => write!(f, "Suffix error: {err}"),
38        }
39    }
40}
41
42impl std::error::Error for MagicTypeIdError {
43    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
44        match self {
45            Self::Prefix(err) => Some(err),
46            Self::Suffix(err) => Some(err),
47        }
48    }
49}
50
51impl From<ValidationError> for MagicTypeIdError {
52    #[cfg_attr(feature = "instrument", instrument(level = "error", fields(error = %err)))]
53    fn from(err: ValidationError) -> Self {
54        #[cfg(feature = "instrument")]
55        error!("Converting ValidationError to MagicTypeIdError: {}", err);
56        Self::Prefix(err)
57    }
58}
59
60impl From<DecodeError> for MagicTypeIdError {
61    #[cfg_attr(feature = "instrument", instrument(level = "error", fields(error = %err)))]
62    fn from(err: DecodeError) -> Self {
63        #[cfg(feature = "instrument")]
64        error!("Converting DecodeError to MagicTypeIdError: {}", err);
65        Self::Suffix(err)
66    }
67}