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
use crate::{Error as ApiError, ErrorCode};
use std::error::Error as StdError;
use std::fmt;

/// Errors returned by the HTTP Client API.
#[derive(Debug)]
pub enum Error {
    /// An error that occurred in the FFI layers.
    FFIError(ApiError),

    /// An HTTP error while processing a request or response.
    Error(http::Error),

    /// Another error from the protocol layer.
    Other(Box<dyn StdError + Send + Sync>),

    /// An invalid HTTP version was found.
    InvalidHttpVersion(u32),
}

impl From<ApiError> for Error {
    fn from(err: ApiError) -> Self {
        Self::FFIError(err)
    }
}

impl From<ErrorCode> for Error {
    fn from(err: ErrorCode) -> Self {
        Self::FFIError(err.into())
    }
}

impl From<std::convert::Infallible> for Error {
    fn from(_: std::convert::Infallible) -> Self {
        unreachable!("Something infallible failed - this should never happen.")
    }
}

impl Error {
    pub(super) fn from_specific(err: impl Into<http::Error>) -> Self {
        Self::Error(err.into())
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::FFIError(e) => write!(f, "Error during FFI call: {e:}",),
            Self::Error(e) => write!(f, "HTTP error: {e:}",),
            Self::InvalidHttpVersion(v) => write!(f, "Invalid HTTP version: {v}",),
            Self::Other(e) => write!(f, "Protocol error: {e:}",),
        }
    }
}

impl StdError for Error {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            Self::FFIError(e) => Some(e),
            Self::Error(e) => Some(e),
            Self::Other(e) => Some(e.as_ref()),
            Self::InvalidHttpVersion(_) => None,
        }
    }
}