summaryrefslogtreecommitdiff
path: root/src/error.rs
blob: fc0a21a6b4890b3c6a1df84db7ae99fcc82a6339 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use std::borrow::Cow;

use maildir::MailEntryError;
use mailparse::MailParseError;
use serde::ser::SerializeStruct as _;
use serde_json::Error as JSONError;

pub type Result<T> = std::result::Result<T, Error>;

#[derive(Debug)]
pub enum Error {
    IoError(std::io::Error),
    MailEntryError(MailEntryError),
    SortOrder(String),
    Setuid(String),
    JSONError(JSONError),
    PathError { msg: String, path: String },
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        write!(f, "{:?}", self)
    }
}

impl std::error::Error for Error {}

impl serde::Serialize for Error {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut state = serializer.serialize_struct("Error", 1)?;
        let err_str: Cow<str> = match self {
            Error::IoError(e) => Cow::Owned(e.to_string()),
            Error::MailEntryError(e) => Cow::Owned(e.to_string()),
            Error::SortOrder(s) => Cow::Borrowed(s),
            Error::Setuid(s) => Cow::Borrowed(s),
            Error::JSONError(e) => Cow::Owned(e.to_string()),
            Error::PathError { msg, path } => Cow::Owned(format!("{} {:?}", msg, path)),
        };
        state.serialize_field("error", &err_str)?;
        state.end()
    }
}

impl From<std::io::Error> for Error {
    fn from(io_err: std::io::Error) -> Self {
        Error::IoError(io_err)
    }
}

impl From<MailEntryError> for Error {
    fn from(me_err: MailEntryError) -> Self {
        Error::MailEntryError(me_err)
    }
}

impl From<MailParseError> for Error {
    fn from(mp_err: MailParseError) -> Self {
        Error::MailEntryError(MailEntryError::ParseError(mp_err))
    }
}

impl From<JSONError> for Error {
    fn from(j_err: JSONError) -> Self {
        Error::JSONError(j_err)
    }
}