1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//! Error conditions.

use std::fmt::{self, Debug, Display, Formatter};

use ruma_api::error::{FromHttpResponseError, IntoHttpError};

/// An error that can occur during client operations.
#[derive(Debug)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub enum Error<E, F> {
    /// Queried endpoint requires authentication but was called on an anonymous client.
    AuthenticationRequired,

    /// Construction of the HTTP request failed (this should never happen).
    IntoHttp(IntoHttpError),

    /// The request's URL is invalid (this should never happen).
    Url(http::Error),

    /// Couldn't obtain an HTTP response (e.g. due to network or DNS issues).
    Response(E),

    /// Converting the HTTP response to one of ruma's types failed.
    FromHttpResponse(FromHttpResponseError<F>),
}

impl<E: Display, F: Display> Display for Error<E, F> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::AuthenticationRequired => {
                write!(f, "The queried endpoint requires authentication but was called with an anonymous client.")
            }
            Self::IntoHttp(err) => write!(f, "HTTP request construction failed: {}", err),
            Self::Url(err) => write!(f, "Invalid URL: {}", err),
            Self::Response(err) => write!(f, "Couldn't obtain a response: {}", err),
            Self::FromHttpResponse(err) => write!(f, "HTTP response conversion failed: {}", err),
        }
    }
}

impl<E, F> From<IntoHttpError> for Error<E, F> {
    fn from(err: IntoHttpError) -> Self {
        Error::IntoHttp(err)
    }
}

#[doc(hidden)]
impl<E, F> From<http::uri::InvalidUri> for Error<E, F> {
    fn from(err: http::uri::InvalidUri) -> Self {
        Error::Url(err.into())
    }
}

#[doc(hidden)]
impl<E, F> From<http::uri::InvalidUriParts> for Error<E, F> {
    fn from(err: http::uri::InvalidUriParts) -> Self {
        Error::Url(err.into())
    }
}

impl<E, F> From<FromHttpResponseError<F>> for Error<E, F> {
    fn from(err: FromHttpResponseError<F>) -> Self {
        Error::FromHttpResponse(err)
    }
}

impl<E: Debug + Display, F: Debug + Display> std::error::Error for Error<E, F> {}