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
use std::error::Error;
use std::fmt;
use std::fmt::Debug;
use std::fmt::Display;
use std::fmt::Formatter;

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

pub struct A2DError {
    message: String,

    /// TODO: See if I can store the real Error value while keeping this
    /// compatible with anyhow::Result
    source: Option<String>,
}

impl A2DError {
    pub(crate) fn new(message: String, source: Option<Box<dyn Error>>) -> A2DError {
        A2DError {
            message,
            source: source.map(|s| format!("{:?}", s)),
        }
    }
}

impl Display for A2DError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "A2DError {}", self.message)?;
        if let Some(source) = &self.source {
            write!(f, ": {}", source)?;
        }
        Ok(())
    }
}

impl Debug for A2DError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "A2DError {}", self.message)?;
        if let Some(source) = &self.source {
            write!(f, ": {:?}", source)?;
        }
        Ok(())
    }
}

impl Error for A2DError {}

impl From<std::io::Error> for A2DError {
    fn from(e: std::io::Error) -> Self {
        A2DError::new(format!("IOError"), Some(Box::new(e)))
    }
}

impl From<image::ImageError> for A2DError {
    fn from(e: image::ImageError) -> Self {
        A2DError::new(format!("ImageError"), Some(Box::new(e)))
    }
}