libjsonutils/
error.rs

1use serde_json::Error as JsonError;
2use std::{
3    fmt::{Display, Formatter, Result as FmtResult},
4    io::Error as IoError,
5    string::FromUtf8Error,
6};
7
8#[derive(Debug)]
9pub enum Error {
10    Json(JsonError),
11    Io(IoError),
12    Utf8(FromUtf8Error),
13    Custom(&'static str),
14}
15
16impl Error {
17    pub(crate) fn json(err: JsonError) -> Self {
18        Self::Json(err)
19    }
20
21    pub(crate) fn io(err: IoError) -> Self {
22        Self::Io(err)
23    }
24
25    pub(crate) fn utf8(err: FromUtf8Error) -> Self {
26        Self::Utf8(err)
27    }
28
29    pub(crate) fn custom(msg: &'static str) -> Self {
30        Self::Custom(msg)
31    }
32}
33
34impl Display for Error {
35    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
36        match self {
37            Self::Json(err) => err.fmt(f),
38            Self::Io(err) => err.fmt(f),
39            Self::Utf8(err) => err.fmt(f),
40            Self::Custom(msg) => write!(f, "{}", msg),
41        }
42    }
43}
44
45#[cfg(feature = "anyhow")]
46impl From<Error> for anyhow::Error {
47    fn from(err: Error) -> Self {
48        match err {
49            Error::Json(err) => anyhow::Error::new(err),
50            Error::Io(err) => anyhow::Error::new(err),
51            Error::Utf8(err) => anyhow::Error::new(err),
52            Error::Custom(msg) => anyhow::Error::msg(msg),
53        }
54    }
55}