jqdata_model/
errors.rs

1use serde::de;
2use std::fmt;
3
4#[derive(Debug)]
5pub enum Error {
6    Server(String),
7    Client(String),
8    Serde(String),
9    Csv(csv::Error),
10    Json(serde_json::Error),
11    Io(std::io::Error),
12    Utf8(std::str::Utf8Error),
13}
14
15impl fmt::Display for Error {
16    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
17        match *self {
18            Error::Server(ref s) => write!(f, "Server error: {}", s),
19            Error::Client(ref s) => write!(f, "Client error: {}", s),
20            Error::Serde(ref s) => write!(f, "Serde error: {}", s),
21            Error::Csv(ref err) => write!(f, "Csv error: {}", err),
22            Error::Json(ref err) => write!(f, "Json error: {}", err),
23            Error::Io(ref err) => write!(f, "Io error: {}", err),
24            Error::Utf8(ref err) => write!(f, "Utf8 error: {}", err),
25        }
26    }
27}
28
29impl std::error::Error for Error {
30    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
31        match *self {
32            Error::Server(..) => None,
33            Error::Client(..) => None,
34            Error::Serde(..) => None,
35            Error::Csv(ref err) => Some(err),
36            Error::Json(ref err) => Some(err),
37            Error::Io(ref err) => Some(err),
38            Error::Utf8(ref err) => Some(err),
39        }
40    }
41}
42
43impl From<csv::Error> for Error {
44    fn from(err: csv::Error) -> Error {
45        Error::Csv(err)
46    }
47}
48
49impl From<serde_json::Error> for Error {
50    fn from(err: serde_json::Error) -> Error {
51        Error::Json(err)
52    }
53}
54
55impl From<std::io::Error> for Error {
56    fn from(err: std::io::Error) -> Error {
57        Error::Io(err)
58    }
59}
60
61impl From<std::string::FromUtf8Error> for Error {
62    fn from(err: std::string::FromUtf8Error) -> Error {
63        Error::Utf8(err.utf8_error())
64    }
65}
66
67impl From<std::num::ParseIntError> for Error {
68    fn from(err: std::num::ParseIntError) -> Error {
69        Error::Server(format!("{}", err))
70    }
71}
72
73/// when deserailizing, the serde framework requires
74/// the ability to convert local error to serde::de::Error
75impl de::Error for Error {
76    fn custom<T>(msg: T) -> Self
77    where
78        T: fmt::Display,
79    {
80        Error::Serde(format!("{}", msg))
81    }
82}