contained_core/
error.rs

1/*
2    appellation: error <module>
3    authors: @FL03
4*/
5//! this module defines the [`Error`] enum and related types for error handling within the
6//! crate.
7#[cfg(feature = "alloc")]
8use alloc::{boxed::Box, string::String};
9
10/// a type alias for a [`Result`](core::result::Result) configured to use the custom [`Error`] type.
11pub type Result<T> = core::result::Result<T, Error>;
12
13/// The [`Error`] implementation defines the possible errors that can occur within the crate.
14#[derive(Debug, thiserror::Error)]
15#[non_exhaustive]
16pub enum Error {
17    // core errors
18    #[error(transparent)]
19    AddrParseError(#[from] core::net::AddrParseError),
20    #[error(transparent)]
21    FmtError(#[from] core::fmt::Error),
22    #[error(transparent)]
23    Utf8Error(#[from] core::str::Utf8Error),
24    // std-dependent errors
25    #[cfg(feature = "std")]
26    #[error(transparent)]
27    IOError(#[from] std::io::Error),
28    // alloc-dependent variants
29    #[cfg(feature = "alloc")]
30    #[error(transparent)]
31    BoxError(#[from] Box<dyn core::error::Error + Send + Sync + 'static>),
32    #[cfg(feature = "alloc")]
33    #[error("Unknown Error: {0}")]
34    Unknown(String),
35}
36
37impl Error {
38    #[cfg(feature = "alloc")]
39    /// a functional constructor for the [`BoxError`](Self::BoxError) variant
40    pub fn boxed<E>(error: E) -> Self
41    where
42        E: core::error::Error + Send + Sync + 'static,
43    {
44        Self::BoxError(Box::new(error))
45    }
46    #[cfg(feature = "alloc")]
47    /// a functional constructor for the [`Unknown`](Self::Unknown) variant
48    pub fn unknown<E>(message: E) -> Self
49    where
50        E: alloc::string::ToString,
51    {
52        Self::Unknown(message.to_string())
53    }
54}
55
56#[cfg(feature = "alloc")]
57impl From<&str> for Error {
58    fn from(value: &str) -> Self {
59        Self::unknown(value)
60    }
61}
62
63#[cfg(feature = "alloc")]
64impl From<String> for Error {
65    fn from(value: String) -> Self {
66        Self::Unknown(value)
67    }
68}