serde_error/
lib.rs

1#![doc = include_str!("../README.md")]
2
3// TODO: once backtrace lands stable, consider trying to serialize the backtrace too? not sure it
4// makes sense though.
5
6#[derive(Clone, serde::Deserialize, serde::Serialize)]
7pub struct Error {
8    description: String,
9    source: Option<Box<Error>>,
10}
11
12impl Error {
13    pub fn new<T>(e: &T) -> Error
14    where
15        T: ?Sized + std::error::Error,
16    {
17        Error {
18            description: e.to_string(),
19            source: e.source().map(|s| Box::new(Error::new(s))),
20        }
21    }
22}
23
24impl std::error::Error for Error {
25    fn source(&self) -> Option<&(dyn 'static + std::error::Error)> {
26        self.source.as_ref().map(|s| &**s as &(dyn 'static + std::error::Error))
27    }
28
29    fn description(&self) -> &str {
30        &self.description
31    }
32}
33
34impl std::fmt::Display for Error {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        write!(f, "{}", self.description)
37    }
38}
39
40impl std::fmt::Debug for Error {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        write!(f, "{}", self.description)
43    }
44}