xml2json_rs/
error.rs

1use std::{error::Error as StdError, fmt};
2
3use quick_xml::Error as XmlError;
4use serde_json::error::Error as JsonError;
5use std::{str::Utf8Error, string::FromUtf8Error};
6
7#[derive(Clone, Debug, PartialEq)]
8pub enum ErrorKind {
9  Syntax,
10  Encoding,
11  Unknown
12}
13
14impl ErrorKind {
15  pub fn to_str(&self) -> &'static str {
16    match *self {
17      ErrorKind::Syntax => "parse",
18      ErrorKind::Encoding => "encoding",
19      ErrorKind::Unknown => "unknown"
20    }
21  }
22}
23
24/// This type represents all possible errors that can occur when converting to or from XML and JSON
25pub struct Error {
26  details: String,
27  desc:    &'static str,
28  kind:    ErrorKind
29}
30
31impl Error {
32  /// Initialize a new Error with `ErrorKind`
33  pub fn new<T: Into<String>>(kind: ErrorKind, detail: T) -> Error {
34    let desc = kind.to_str();
35    Error {
36      kind,
37      desc,
38      details: detail.into()
39    }
40  }
41
42  /// Error kind
43  pub fn kind(&self) -> ErrorKind {
44    self.kind.clone()
45  }
46
47  /// Error details
48  pub fn details(&self) -> String {
49    self.details.clone()
50  }
51}
52
53impl fmt::Display for Error {
54  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
55    write!(f, "{}: {}", self.kind.to_str(), self.details)
56  }
57}
58
59impl fmt::Debug for Error {
60  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
61    write!(f, "{}", self)
62  }
63}
64
65impl StdError for Error {
66  fn description(&self) -> &str {
67    self.desc
68  }
69}
70
71impl From<JsonError> for Error {
72  fn from(e: JsonError) -> Self {
73    Error::new(ErrorKind::Syntax, format!("{}", e))
74  }
75}
76
77impl From<XmlError> for Error {
78  fn from(e: XmlError) -> Self {
79    Error::new(ErrorKind::Unknown, format!("{}", e))
80  }
81}
82
83impl From<FromUtf8Error> for Error {
84  fn from(e: FromUtf8Error) -> Self {
85    Error::new(ErrorKind::Encoding, format!("{}", e))
86  }
87}
88
89impl From<Utf8Error> for Error {
90  fn from(e: Utf8Error) -> Self {
91    Error::new(ErrorKind::Encoding, format!("{}", e))
92  }
93}