1 | #![cfg_attr (target_arch = "wasm32" , allow(unused))] |
2 | use std::error::Error as StdError; |
3 | use std::fmt; |
4 | use std::io; |
5 | |
6 | use crate::{StatusCode, Url}; |
7 | |
8 | /// A `Result` alias where the `Err` case is `reqwest::Error`. |
9 | pub type Result<T> = std::result::Result<T, Error>; |
10 | |
11 | /// The Errors that may occur when processing a `Request`. |
12 | /// |
13 | /// Note: Errors may include the full URL used to make the `Request`. If the URL |
14 | /// contains sensitive information (e.g. an API key as a query parameter), be |
15 | /// sure to remove it ([`without_url`](Error::without_url)) |
16 | pub struct Error { |
17 | inner: Box<Inner>, |
18 | } |
19 | |
20 | pub(crate) type BoxError = Box<dyn StdError + Send + Sync>; |
21 | |
22 | struct Inner { |
23 | kind: Kind, |
24 | source: Option<BoxError>, |
25 | url: Option<Url>, |
26 | } |
27 | |
28 | impl Error { |
29 | pub(crate) fn new<E>(kind: Kind, source: Option<E>) -> Error |
30 | where |
31 | E: Into<BoxError>, |
32 | { |
33 | Error { |
34 | inner: Box::new(Inner { |
35 | kind, |
36 | source: source.map(Into::into), |
37 | url: None, |
38 | }), |
39 | } |
40 | } |
41 | |
42 | /// Returns a possible URL related to this error. |
43 | /// |
44 | /// # Examples |
45 | /// |
46 | /// ``` |
47 | /// # async fn run() { |
48 | /// // displays last stop of a redirect loop |
49 | /// let response = reqwest::get("http://site.with.redirect.loop" ).await; |
50 | /// if let Err(e) = response { |
51 | /// if e.is_redirect() { |
52 | /// if let Some(final_stop) = e.url() { |
53 | /// println!("redirect loop at {final_stop}" ); |
54 | /// } |
55 | /// } |
56 | /// } |
57 | /// # } |
58 | /// ``` |
59 | pub fn url(&self) -> Option<&Url> { |
60 | self.inner.url.as_ref() |
61 | } |
62 | |
63 | /// Returns a mutable reference to the URL related to this error |
64 | /// |
65 | /// This is useful if you need to remove sensitive information from the URL |
66 | /// (e.g. an API key in the query), but do not want to remove the URL |
67 | /// entirely. |
68 | pub fn url_mut(&mut self) -> Option<&mut Url> { |
69 | self.inner.url.as_mut() |
70 | } |
71 | |
72 | /// Add a url related to this error (overwriting any existing) |
73 | pub fn with_url(mut self, url: Url) -> Self { |
74 | self.inner.url = Some(url); |
75 | self |
76 | } |
77 | |
78 | /// Strip the related url from this error (if, for example, it contains |
79 | /// sensitive information) |
80 | pub fn without_url(mut self) -> Self { |
81 | self.inner.url = None; |
82 | self |
83 | } |
84 | |
85 | /// Returns true if the error is from a type Builder. |
86 | pub fn is_builder(&self) -> bool { |
87 | matches!(self.inner.kind, Kind::Builder) |
88 | } |
89 | |
90 | /// Returns true if the error is from a `RedirectPolicy`. |
91 | pub fn is_redirect(&self) -> bool { |
92 | matches!(self.inner.kind, Kind::Redirect) |
93 | } |
94 | |
95 | /// Returns true if the error is from `Response::error_for_status`. |
96 | pub fn is_status(&self) -> bool { |
97 | matches!(self.inner.kind, Kind::Status(_)) |
98 | } |
99 | |
100 | /// Returns true if the error is related to a timeout. |
101 | pub fn is_timeout(&self) -> bool { |
102 | let mut source = self.source(); |
103 | |
104 | while let Some(err) = source { |
105 | if err.is::<TimedOut>() { |
106 | return true; |
107 | } |
108 | if let Some(io) = err.downcast_ref::<io::Error>() { |
109 | if io.kind() == io::ErrorKind::TimedOut { |
110 | return true; |
111 | } |
112 | } |
113 | source = err.source(); |
114 | } |
115 | |
116 | false |
117 | } |
118 | |
119 | /// Returns true if the error is related to the request |
120 | pub fn is_request(&self) -> bool { |
121 | matches!(self.inner.kind, Kind::Request) |
122 | } |
123 | |
124 | #[cfg (not(target_arch = "wasm32" ))] |
125 | /// Returns true if the error is related to connect |
126 | pub fn is_connect(&self) -> bool { |
127 | let mut source = self.source(); |
128 | |
129 | while let Some(err) = source { |
130 | if let Some(hyper_err) = err.downcast_ref::<hyper::Error>() { |
131 | if hyper_err.is_connect() { |
132 | return true; |
133 | } |
134 | } |
135 | |
136 | source = err.source(); |
137 | } |
138 | |
139 | false |
140 | } |
141 | |
142 | /// Returns true if the error is related to the request or response body |
143 | pub fn is_body(&self) -> bool { |
144 | matches!(self.inner.kind, Kind::Body) |
145 | } |
146 | |
147 | /// Returns true if the error is related to decoding the response's body |
148 | pub fn is_decode(&self) -> bool { |
149 | matches!(self.inner.kind, Kind::Decode) |
150 | } |
151 | |
152 | /// Returns the status code, if the error was generated from a response. |
153 | pub fn status(&self) -> Option<StatusCode> { |
154 | match self.inner.kind { |
155 | Kind::Status(code) => Some(code), |
156 | _ => None, |
157 | } |
158 | } |
159 | |
160 | // private |
161 | |
162 | #[allow (unused)] |
163 | pub(crate) fn into_io(self) -> io::Error { |
164 | io::Error::new(io::ErrorKind::Other, self) |
165 | } |
166 | } |
167 | |
168 | impl fmt::Debug for Error { |
169 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
170 | let mut builder: DebugStruct<'_, '_> = f.debug_struct(name:"reqwest::Error" ); |
171 | |
172 | builder.field(name:"kind" , &self.inner.kind); |
173 | |
174 | if let Some(ref url: &Url) = self.inner.url { |
175 | builder.field(name:"url" , value:url); |
176 | } |
177 | if let Some(ref source: &Box) = self.inner.source { |
178 | builder.field(name:"source" , value:source); |
179 | } |
180 | |
181 | builder.finish() |
182 | } |
183 | } |
184 | |
185 | impl fmt::Display for Error { |
186 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
187 | match self.inner.kind { |
188 | Kind::Builder => f.write_str("builder error" )?, |
189 | Kind::Request => f.write_str("error sending request" )?, |
190 | Kind::Body => f.write_str("request or response body error" )?, |
191 | Kind::Decode => f.write_str("error decoding response body" )?, |
192 | Kind::Redirect => f.write_str("error following redirect" )?, |
193 | Kind::Upgrade => f.write_str("error upgrading connection" )?, |
194 | Kind::Status(ref code) => { |
195 | let prefix = if code.is_client_error() { |
196 | "HTTP status client error" |
197 | } else { |
198 | debug_assert!(code.is_server_error()); |
199 | "HTTP status server error" |
200 | }; |
201 | write!(f, " {prefix} ( {code})" )?; |
202 | } |
203 | }; |
204 | |
205 | if let Some(url) = &self.inner.url { |
206 | write!(f, " for url ( {url})" )?; |
207 | } |
208 | |
209 | if let Some(e) = &self.inner.source { |
210 | write!(f, ": {e}" )?; |
211 | } |
212 | |
213 | Ok(()) |
214 | } |
215 | } |
216 | |
217 | impl StdError for Error { |
218 | fn source(&self) -> Option<&(dyn StdError + 'static)> { |
219 | self.inner.source.as_ref().map(|e: &Box| &**e as _) |
220 | } |
221 | } |
222 | |
223 | #[cfg (target_arch = "wasm32" )] |
224 | impl From<crate::error::Error> for wasm_bindgen::JsValue { |
225 | fn from(err: Error) -> wasm_bindgen::JsValue { |
226 | js_sys::Error::from(err).into() |
227 | } |
228 | } |
229 | |
230 | #[cfg (target_arch = "wasm32" )] |
231 | impl From<crate::error::Error> for js_sys::Error { |
232 | fn from(err: Error) -> js_sys::Error { |
233 | js_sys::Error::new(&format!(" {err}" )) |
234 | } |
235 | } |
236 | |
237 | #[derive (Debug)] |
238 | pub(crate) enum Kind { |
239 | Builder, |
240 | Request, |
241 | Redirect, |
242 | Status(StatusCode), |
243 | Body, |
244 | Decode, |
245 | Upgrade, |
246 | } |
247 | |
248 | // constructors |
249 | |
250 | pub(crate) fn builder<E: Into<BoxError>>(e: E) -> Error { |
251 | Error::new(Kind::Builder, source:Some(e)) |
252 | } |
253 | |
254 | pub(crate) fn body<E: Into<BoxError>>(e: E) -> Error { |
255 | Error::new(Kind::Body, source:Some(e)) |
256 | } |
257 | |
258 | pub(crate) fn decode<E: Into<BoxError>>(e: E) -> Error { |
259 | Error::new(Kind::Decode, source:Some(e)) |
260 | } |
261 | |
262 | pub(crate) fn request<E: Into<BoxError>>(e: E) -> Error { |
263 | Error::new(Kind::Request, source:Some(e)) |
264 | } |
265 | |
266 | pub(crate) fn redirect<E: Into<BoxError>>(e: E, url: Url) -> Error { |
267 | Error::new(Kind::Redirect, source:Some(e)).with_url(url) |
268 | } |
269 | |
270 | pub(crate) fn status_code(url: Url, status: StatusCode) -> Error { |
271 | Error::new(Kind::Status(status), source:None::<Error>).with_url(url) |
272 | } |
273 | |
274 | pub(crate) fn url_bad_scheme(url: Url) -> Error { |
275 | Error::new(Kind::Builder, source:Some(BadScheme)).with_url(url) |
276 | } |
277 | |
278 | pub(crate) fn url_invalid_uri(url: Url) -> Error { |
279 | Error::new(Kind::Builder, source:Some("Parsed Url is not a valid Uri" )).with_url(url) |
280 | } |
281 | |
282 | if_wasm! { |
283 | pub(crate) fn wasm(js_val: wasm_bindgen::JsValue) -> BoxError { |
284 | format!(" {js_val:?}" ).into() |
285 | } |
286 | } |
287 | |
288 | pub(crate) fn upgrade<E: Into<BoxError>>(e: E) -> Error { |
289 | Error::new(Kind::Upgrade, source:Some(e)) |
290 | } |
291 | |
292 | // io::Error helpers |
293 | |
294 | #[allow (unused)] |
295 | pub(crate) fn into_io(e: Error) -> io::Error { |
296 | e.into_io() |
297 | } |
298 | |
299 | #[allow (unused)] |
300 | pub(crate) fn decode_io(e: io::Error) -> Error { |
301 | if e.get_ref().map(|r| r.is::<Error>()).unwrap_or(default:false) { |
302 | *e.into_inner() |
303 | .expect("io::Error::get_ref was Some(_)" ) |
304 | .downcast::<Error>() |
305 | .expect(msg:"StdError::is() was true" ) |
306 | } else { |
307 | decode(e) |
308 | } |
309 | } |
310 | |
311 | // internal Error "sources" |
312 | |
313 | #[derive (Debug)] |
314 | pub(crate) struct TimedOut; |
315 | |
316 | impl fmt::Display for TimedOut { |
317 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
318 | f.write_str(data:"operation timed out" ) |
319 | } |
320 | } |
321 | |
322 | impl StdError for TimedOut {} |
323 | |
324 | #[derive (Debug)] |
325 | pub(crate) struct BadScheme; |
326 | |
327 | impl fmt::Display for BadScheme { |
328 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
329 | f.write_str(data:"URL scheme is not allowed" ) |
330 | } |
331 | } |
332 | |
333 | impl StdError for BadScheme {} |
334 | |
335 | #[cfg (test)] |
336 | mod tests { |
337 | use super::*; |
338 | |
339 | fn assert_send<T: Send>() {} |
340 | fn assert_sync<T: Sync>() {} |
341 | |
342 | #[test ] |
343 | fn test_source_chain() { |
344 | let root = Error::new(Kind::Request, None::<Error>); |
345 | assert!(root.source().is_none()); |
346 | |
347 | let link = super::body(root); |
348 | assert!(link.source().is_some()); |
349 | assert_send::<Error>(); |
350 | assert_sync::<Error>(); |
351 | } |
352 | |
353 | #[test ] |
354 | fn mem_size_of() { |
355 | use std::mem::size_of; |
356 | assert_eq!(size_of::<Error>(), size_of::<usize>()); |
357 | } |
358 | |
359 | #[test ] |
360 | fn roundtrip_io_error() { |
361 | let orig = super::request("orig" ); |
362 | // Convert reqwest::Error into an io::Error... |
363 | let io = orig.into_io(); |
364 | // Convert that io::Error back into a reqwest::Error... |
365 | let err = super::decode_io(io); |
366 | // It should have pulled out the original, not nested it... |
367 | match err.inner.kind { |
368 | Kind::Request => (), |
369 | _ => panic!(" {err:?}" ), |
370 | } |
371 | } |
372 | |
373 | #[test ] |
374 | fn from_unknown_io_error() { |
375 | let orig = io::Error::new(io::ErrorKind::Other, "orly" ); |
376 | let err = super::decode_io(orig); |
377 | match err.inner.kind { |
378 | Kind::Decode => (), |
379 | _ => panic!(" {err:?}" ), |
380 | } |
381 | } |
382 | |
383 | #[test ] |
384 | fn is_timeout() { |
385 | let err = super::request(super::TimedOut); |
386 | assert!(err.is_timeout()); |
387 | |
388 | let io = io::Error::new(io::ErrorKind::Other, err); |
389 | let nested = super::request(io); |
390 | assert!(nested.is_timeout()); |
391 | } |
392 | } |
393 | |