hcl/
error.rs

1//! The `Error` and `Result` types used by this crate.
2use crate::edit::parser;
3use crate::eval;
4use serde::{de, ser};
5use std::fmt::{self, Display};
6use std::io;
7use std::str::Utf8Error;
8
9/// The result type used by this crate.
10pub type Result<T, E = Error> = std::result::Result<T, E>;
11
12/// The error type used by this crate.
13#[derive(Debug)]
14#[non_exhaustive]
15pub enum Error {
16    /// Represents a generic error message.
17    Message(String),
18    /// Represents an error that resulted from invalid UTF8 input.
19    Utf8(Utf8Error),
20    /// Represents generic IO errors.
21    Io(io::Error),
22    /// Represents errors during expression evaluation.
23    Eval(eval::Error),
24    /// Represents errors while parsing HCL.
25    Parse(parser::Error),
26}
27
28impl Error {
29    pub(crate) fn new<T>(msg: T) -> Error
30    where
31        T: Display,
32    {
33        Error::Message(msg.to_string())
34    }
35}
36
37impl Display for Error {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        match self {
40            Error::Io(err) => write!(f, "{err}"),
41            Error::Utf8(err) => write!(f, "{err}"),
42            Error::Message(msg) => write!(f, "{msg}"),
43            Error::Eval(err) => write!(f, "eval error: {err}"),
44            Error::Parse(err) => write!(f, "{err}"),
45        }
46    }
47}
48
49impl From<io::Error> for Error {
50    fn from(err: io::Error) -> Self {
51        Error::Io(err)
52    }
53}
54
55impl From<Utf8Error> for Error {
56    fn from(err: Utf8Error) -> Self {
57        Error::Utf8(err)
58    }
59}
60
61impl From<parser::Error> for Error {
62    fn from(err: parser::Error) -> Self {
63        Error::Parse(err)
64    }
65}
66
67impl From<eval::Error> for Error {
68    fn from(err: eval::Error) -> Self {
69        Error::Eval(err)
70    }
71}
72
73impl std::error::Error for Error {}
74
75impl ser::Error for Error {
76    fn custom<T: Display>(msg: T) -> Self {
77        Error::new(msg)
78    }
79}
80
81impl de::Error for Error {
82    fn custom<T: Display>(msg: T) -> Self {
83        Error::new(msg)
84    }
85}