error.rs

 1// Copyright (c) 2020 lumi <lumi@pew.im>
 2// Copyright (c) 2020 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
 3// Copyright (c) 2020 Bastien Orivel <eijebong+minidom@bananium.fr>
 4// Copyright (c) 2020 Astro <astro@spaceboyz.net>
 5// Copyright (c) 2020 Maxime “pep” Buquet <pep@bouah.net>
 6// Copyright (c) 2020 Matt Bilker <me@mbilker.us>
 7//
 8// This Source Code Form is subject to the terms of the Mozilla Public
 9// License, v. 2.0. If a copy of the MPL was not distributed with this
10// file, You can obtain one at http://mozilla.org/MPL/2.0/.
11
12//! Provides an error type for this crate.
13
14use std::convert::From;
15use std::error::Error as StdError;
16
17/// Our main error type.
18#[derive(Debug)]
19pub enum Error {
20    /// Error from rxml parsing or writing
21    XmlError(rxml::Error),
22
23    /// An error which is returned when the end of the document was reached prematurely.
24    EndOfDocument,
25
26    /// An error which is returned when an element being serialized doesn't contain a prefix
27    /// (be it None or Some(_)).
28    InvalidPrefix,
29
30    /// An error which is returned when an element doesn't contain a namespace
31    MissingNamespace,
32
33    /// An error which is returned when a prefixed is defined twice
34    DuplicatePrefix,
35}
36
37impl StdError for Error {
38    fn cause(&self) -> Option<&dyn StdError> {
39        match self {
40            Error::XmlError(e) => Some(e),
41            Error::EndOfDocument => None,
42            Error::InvalidPrefix => None,
43            Error::MissingNamespace => None,
44            Error::DuplicatePrefix => None,
45        }
46    }
47}
48
49impl std::fmt::Display for Error {
50    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
51        match self {
52            Error::XmlError(e) => write!(fmt, "XML error: {}", e),
53            Error::EndOfDocument => {
54                write!(fmt, "the end of the document has been reached prematurely")
55            }
56            Error::InvalidPrefix => write!(fmt, "the prefix is invalid"),
57            Error::MissingNamespace => write!(fmt, "the XML element is missing a namespace",),
58            Error::DuplicatePrefix => write!(fmt, "the prefix is already defined"),
59        }
60    }
61}
62
63impl From<rxml::Error> for Error {
64    fn from(err: rxml::Error) -> Error {
65        Error::XmlError(err)
66    }
67}
68
69impl From<rxml::error::XmlError> for Error {
70    fn from(err: rxml::error::XmlError) -> Error {
71        Error::XmlError(err.into())
72    }
73}
74
75/// Our simplified Result type.
76pub type Result<T> = ::std::result::Result<T, Error>;