facet_args/
error.rs

1use facet_deserialize::{DeserError, DeserErrorKind};
2use facet_reflect::ReflectError;
3
4/// Error deserializing the Arguments
5pub struct ArgsError {
6    /// Type of error
7    pub kind: ArgsErrorKind,
8}
9
10impl ArgsError {
11    /// Create a new error.
12    pub fn new(kind: ArgsErrorKind) -> Self {
13        Self { kind }
14    }
15    /// The message for this specific error.
16    pub fn message(&self) -> String {
17        match &self.kind {
18            ArgsErrorKind::GenericReflect(reflect_error) => {
19                format!("Error while reflecting type: {reflect_error}")
20            }
21            ArgsErrorKind::GenericArgsError(message) => format!("Args error: {message}"),
22        }
23    }
24}
25
26impl core::fmt::Display for ArgsError {
27    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
28        write!(f, "{}", self.message())
29    }
30}
31
32impl core::fmt::Debug for ArgsError {
33    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
34        core::fmt::Display::fmt(self, f)
35    }
36}
37
38impl core::error::Error for ArgsError {}
39
40/// Type of error.
41#[derive(Debug, PartialEq)]
42pub enum ArgsErrorKind {
43    /// Any error from facet
44    GenericReflect(ReflectError),
45    /// Parsing arguments error
46    GenericArgsError(String),
47}
48
49/// Convert a DeserError to an ArgsError
50pub fn from_deser_error(error: DeserError<'_>) -> ArgsError {
51    match error.kind {
52        DeserErrorKind::UnexpectedEof { wanted } => ArgsError::new(
53            ArgsErrorKind::GenericArgsError(format!("Unexpected end of input: {}", wanted)),
54        ),
55        DeserErrorKind::MissingField(field) => ArgsError::new(ArgsErrorKind::GenericArgsError(
56            format!("Missing required field: {}", field),
57        )),
58        DeserErrorKind::ReflectError(e) => ArgsError::new(ArgsErrorKind::GenericReflect(e)),
59        DeserErrorKind::UnknownField { field_name, .. } => ArgsError::new(
60            ArgsErrorKind::GenericArgsError(format!("Unknown field: {}", field_name)),
61        ),
62        DeserErrorKind::Unimplemented(msg) => ArgsError::new(ArgsErrorKind::GenericArgsError(
63            format!("Unimplemented feature: {}", msg),
64        )),
65        _ => ArgsError::new(ArgsErrorKind::GenericArgsError(format!(
66            "Deserialization error: {}",
67            error
68        ))),
69    }
70}