aboutsummaryrefslogtreecommitdiff
path: root/src/error.rs
blob: 518b0e90483bd2f6d3adb01639840852acb63c3a (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
use std::error::Error;
use std::fmt::Display;
use std::io;

pub type ArchiveResult<T, E> = Result<T, ArchiveError<E>>;

#[derive(Debug)]
pub enum ArchiveError<E: Error> {
    Io { error: io::Error },
    Serde { message: String },
    Archivator { module: String, error: E },
}

impl<E: Error> From<io::Error> for ArchiveError<E> {
    fn from(value: io::Error) -> Self {
        Self::Io { error: value }
    }
}

impl<E: Error + PartialEq> PartialEq<E> for ArchiveError<E> {
    fn eq(&self, other: &E) -> bool {
        match self {
            Self::Archivator { error, .. } => error == other,
            _ => false,
        }
    }
}

impl<E: Error> Display for ArchiveError<E> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io { error } => writeln!(f, "IO: {error}"),
            Self::Serde { message } => writeln!(f, "Serde: {message}"),
            Self::Archivator { module, error } => writeln!(f, "{module}: {error}"),
        }
    }
}

impl<E: Error> Error for ArchiveError<E> {}

impl<E: Error> serde::ser::Error for ArchiveError<E> {
    fn custom<T: Display>(msg: T) -> Self {
        Self::Serde {
            message: msg.to_string(),
        }
    }
}

impl<E: Error> serde::de::Error for ArchiveError<E> {
    fn custom<T: Display>(msg: T) -> Self {
        Self::Serde {
            message: msg.to_string(),
        }
    }
}