1use std::error;
2use std::fmt;
3use std::io;
4
5#[derive(Debug)]
7pub struct Error {
8 original: Option<Box<dyn error::Error>>,
9 msg: String,
10}
11
12impl Error {
13 pub(crate) fn new<S>(msg: S) -> Self
14 where
15 S: Into<String>,
16 {
17 Self {
18 original: None,
19 msg: msg.into(),
20 }
21 }
22
23 pub(crate) fn with_source<S, E>(msg: S, source: E) -> Self
24 where
25 S: Into<String>,
26 E: error::Error + 'static,
27 {
28 Self {
29 original: Some(Box::new(source)),
30 msg: msg.into(),
31 }
32 }
33
34 pub(crate) fn bail<T, S>(msg: S) -> Result<T, Self>
35 where
36 S: Into<String>,
37 {
38 Err(Error::new(msg))
39 }
40}
41
42impl fmt::Display for Error {
43 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
44 write!(f, "{}", self.msg)
45 }
46}
47
48impl From<io::Error> for Error {
49 fn from(error: io::Error) -> Self {
50 let msg = error.to_string();
51 Self {
52 original: Some(Box::new(error)),
53 msg,
54 }
55 }
56}
57
58impl error::Error for Error {
59 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
60 self.original.as_ref().map(|o| o.as_ref())
61 }
62}