media_types/
error.rs

1use std::error;
2use std::fmt::{self, Display};
3use std::str::Utf8Error;
4use std::string::FromUtf8Error;
5
6use charsets;
7
8
9#[derive(Clone, Copy, Debug, Eq, PartialEq)]
10/// Defines an Error type for media types.
11pub enum Error {
12    /// Parsing the given string as a media type failed.
13    Invalid,
14    /// The media type does not have this parameter.
15    NotFound,
16    /// Decoding a string as UTF-8 (or ASCII) failed.
17    Utf8Error(Utf8Error),
18}
19
20impl error::Error for Error {
21    fn description(&self) -> &str {
22        match *self {
23            Error::Invalid => "given media type is invalid",
24            Error::NotFound => "given parameter not found",
25            Error::Utf8Error(_) => "decoding as UTF-8 failed",
26        }
27    }
28
29    fn cause(&self) -> Option<&error::Error> {
30        if let Error::Utf8Error(ref error) = *self {
31            Some(error)
32        } else {
33            None
34        }
35    }
36}
37
38impl Display for Error {
39    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
40        f.write_str(error::Error::description(self))
41    }
42}
43
44impl From<charsets::Error> for Error {
45    fn from(_: charsets::Error) -> Error {
46        Error::Invalid
47    }
48}
49
50impl From<FromUtf8Error> for Error {
51    fn from(err: FromUtf8Error) -> Error {
52        Error::Utf8Error(err.utf8_error())
53    }
54}
55
56/// Result type used for this library.
57pub type Result<T> = ::std::result::Result<T, Error>;