Skip to main content

timvw_rust_runtime/
error.rs

1use std::error::Error as StdError;
2use std::fmt;
3
4use crate::BoxError;
5
6/// An error building a request, sending it, or reading the response body.
7pub struct Error {
8    kind: Kind,
9    source: Option<BoxError>,
10}
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13enum Kind {
14    Builder,
15    Request,
16    Body,
17    Decode,
18    Io,
19}
20
21impl Error {
22    pub(crate) fn builder(source: impl Into<BoxError>) -> Self {
23        Self {
24            kind: Kind::Builder,
25            source: Some(source.into()),
26        }
27    }
28
29    pub(crate) fn request(source: impl Into<BoxError>) -> Self {
30        Self {
31            kind: Kind::Request,
32            source: Some(source.into()),
33        }
34    }
35
36    pub(crate) fn body(source: impl Into<BoxError>) -> Self {
37        Self {
38            kind: Kind::Body,
39            source: Some(source.into()),
40        }
41    }
42
43    pub(crate) fn decode(source: impl Into<BoxError>) -> Self {
44        Self {
45            kind: Kind::Decode,
46            source: Some(source.into()),
47        }
48    }
49
50    pub(crate) fn io(source: impl Into<BoxError>) -> Self {
51        Self {
52            kind: Kind::Io,
53            source: Some(source.into()),
54        }
55    }
56
57    /// The request could not be built: an invalid URL, header, or body.
58    pub fn is_builder(&self) -> bool {
59        self.kind == Kind::Builder
60    }
61
62    /// The service failed to send the request or to receive a response: connection refused, a timeout layer gave up,
63    /// and so on. [`Error::source`](std::error::Error::source) is the service's error.
64    pub fn is_request(&self) -> bool {
65        self.kind == Kind::Request
66    }
67
68    /// Reading the response body failed.
69    pub fn is_body(&self) -> bool {
70        self.kind == Kind::Body
71    }
72
73    /// The response body could not be decoded.
74    pub fn is_decode(&self) -> bool {
75        self.kind == Kind::Decode
76    }
77
78    /// A file could not be read or written: an [`Upload`](crate::Upload) whose file is missing, or
79    /// [`Response::save_to`](crate::Response::save_to) failing to write. [`Error::source`](std::error::Error::source)
80    /// is the `std::io::Error`.
81    pub fn is_io(&self) -> bool {
82        self.kind == Kind::Io
83    }
84
85    /// Whether the request timed out: a reqwest timeout, tower's `timeout` layer, or an
86    /// [`idle_timeout`](crate::sse::Events::idle_timeout) of server-sent events.
87    pub fn is_timeout(&self) -> bool {
88        let mut source: Option<&(dyn StdError + 'static)> = self.source.as_deref().map(|e| e as _);
89        while let Some(error) = source {
90            if error.to_string() == "request timed out" || error.is::<TimedOut>() {
91                return true;
92            }
93            #[cfg(feature = "reqwest")]
94            if let Some(error) = error.downcast_ref::<reqwest::Error>() {
95                if error.is_timeout() {
96                    return true;
97                }
98            }
99            source = error.source();
100        }
101        false
102    }
103
104    /// Whether connecting to the server failed (only known for reqwest, and not on WebAssembly, where `fetch` does not
105    /// tell).
106    pub fn is_connect(&self) -> bool {
107        #[cfg(all(feature = "reqwest", not(target_family = "wasm")))]
108        {
109            let mut source: Option<&(dyn StdError + 'static)> =
110                self.source.as_deref().map(|e| e as _);
111            while let Some(error) = source {
112                if let Some(error) = error.downcast_ref::<reqwest::Error>() {
113                    if error.is_connect() {
114                        return true;
115                    }
116                }
117                source = error.source();
118            }
119        }
120        false
121    }
122}
123
124impl fmt::Debug for Error {
125    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126        f.debug_struct("Error")
127            .field("kind", &self.kind)
128            .field("source", &self.source)
129            .finish()
130    }
131}
132
133impl fmt::Display for Error {
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        let what = match self.kind {
136            Kind::Builder => "error building the request",
137            Kind::Request => "error sending the request",
138            Kind::Body => "error reading the response body",
139            Kind::Decode => "error decoding the response body",
140            Kind::Io => "I/O error",
141        };
142        match &self.source {
143            Some(source) => write!(f, "{what}: {source}"),
144            None => f.write_str(what),
145        }
146    }
147}
148
149impl StdError for Error {
150    fn source(&self) -> Option<&(dyn StdError + 'static)> {
151        self.source.as_deref().map(|e| e as _)
152    }
153}
154
155/// Nothing arrived within a time limit, such as an [`idle_timeout`](crate::sse::Events::idle_timeout).
156#[derive(Debug)]
157#[cfg_attr(not(feature = "time"), allow(dead_code))]
158pub(crate) struct TimedOut(pub(crate) String);
159
160impl fmt::Display for TimedOut {
161    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162        f.write_str(&self.0)
163    }
164}
165
166impl StdError for TimedOut {}