google_cloud_gax/error/core_error.rs
1// Copyright 2024 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use super::CredentialsError;
16use super::rpc::Status;
17use http::HeaderMap;
18use std::error::Error as StdError;
19
20type BoxError = Box<dyn StdError + Send + Sync>;
21
22/// The core error returned by all client libraries.
23///
24/// The client libraries report errors from multiple sources. For example, the
25/// service may return an error, the transport may be unable to create the
26/// necessary connection to make a request, the request may timeout before a
27/// response is received, the retry policy may be exhausted, or the library may
28/// be unable to format the request due to invalid or missing application
29/// application inputs.
30///
31/// Most applications will just return the error or log it, without any further
32/// action. However, some applications may need to interrogate the error
33/// details. This type offers a series of predicates to determine the error
34/// kind. The type also offers accessors to query the most common error details.
35/// Applications can query the error [source][std::error::Error::source] for
36/// deeper information.
37///
38/// # Example
39/// ```
40/// use google_cloud_gax::error::Error;
41/// match example_function() {
42/// Err(e) if matches!(e.status(), Some(_)) => {
43/// println!("service error {e}, debug using {:?}", e.status().unwrap());
44/// },
45/// Err(e) if e.is_timeout() => { println!("not enough time {e}"); },
46/// Err(e) => { println!("some other error {e}"); },
47/// Ok(_) => { println!("success, how boring"); },
48/// }
49///
50/// fn example_function() -> Result<String, Error> {
51/// // ... details omitted ...
52/// # use google_cloud_gax::error::rpc::{Code, Status};
53/// # Err(Error::service(Status::default().set_code(Code::NotFound).set_message("NOT FOUND")))
54/// }
55/// ```
56#[derive(Debug)]
57pub struct Error {
58 kind: ErrorKind,
59 source: Option<BoxError>,
60}
61
62impl Error {
63 /// Creates an error with the information returned by Google Cloud services.
64 ///
65 /// # Example
66 /// ```
67 /// use google_cloud_gax::error::Error;
68 /// use google_cloud_gax::error::rpc::{Code, Status};
69 /// let status = Status::default().set_code(Code::NotFound).set_message("NOT FOUND");
70 /// let error = Error::service(status.clone());
71 /// assert_eq!(error.status(), Some(&status));
72 /// ```
73 pub fn service(status: Status) -> Self {
74 let details = ServiceDetails {
75 status,
76 status_code: None,
77 headers: None,
78 };
79 Self {
80 kind: ErrorKind::Service(Box::new(details)),
81 source: None,
82 }
83 }
84
85 /// Creates an error representing a timeout.
86 ///
87 /// # Example
88 /// ```
89 /// use std::error::Error as _;
90 /// use google_cloud_gax::error::Error;
91 /// let error = Error::timeout("simulated timeout");
92 /// assert!(error.is_timeout());
93 /// assert!(error.source().is_some());
94 /// ```
95 pub fn timeout<T: Into<BoxError>>(source: T) -> Self {
96 Self {
97 kind: ErrorKind::Timeout,
98 source: Some(source.into()),
99 }
100 }
101
102 /// The request could not be completed before its deadline.
103 ///
104 /// This is always a client-side generated error. Note that the request may
105 /// or may not have started, and it may or may not complete in the service.
106 /// If the request mutates any state in the service, it may or may not be
107 /// safe to attempt the request again.
108 ///
109 /// # Troubleshooting
110 ///
111 /// The most common cause of this problem is setting a timeout value that is
112 /// based on the observed latency when the service is not under load.
113 /// Consider increasing the timeout value to handle temporary latency
114 /// increases too.
115 ///
116 /// It could also indicate a congestion in the network, a service outage, or
117 /// a service that is under load and will take time to scale up.
118 pub fn is_timeout(&self) -> bool {
119 matches!(self.kind, ErrorKind::Timeout)
120 }
121
122 /// Creates an error representing an exhausted policy.
123 ///
124 /// # Example
125 /// ```
126 /// use std::error::Error as _;
127 /// use google_cloud_gax::error::Error;
128 /// let error = Error::exhausted("too many retry attempts");
129 /// assert!(error.is_exhausted());
130 /// assert!(error.source().is_some());
131 /// ```
132 pub fn exhausted<T: Into<BoxError>>(source: T) -> Self {
133 Self {
134 kind: ErrorKind::Exhausted,
135 source: Some(source.into()),
136 }
137 }
138
139 /// The request could not complete be before the retry policy expired.
140 ///
141 /// This is always a client-side generated error, but it may be the result
142 /// of multiple errors received from the service.
143 ///
144 /// # Troubleshooting
145 ///
146 /// The most common cause of this problem is a transient problem that lasts
147 /// longer than your retry policy. For example, your retry policy may
148 /// effectively be exhausted after a few seconds, but some services may take
149 /// minutes to recover.
150 ///
151 /// If your application can tolerate longer recovery times then extend the
152 /// retry policy. Otherwise consider recovery at a higher level, such as
153 /// seeking human intervention, switching the workload to a different
154 /// location, failing the batch job and starting from a previous checkpoint,
155 /// or even presenting an error to the application user.
156 pub fn is_exhausted(&self) -> bool {
157 matches!(self.kind, ErrorKind::Exhausted)
158 }
159
160 /// Not part of the public API, subject to change without notice.
161 ///
162 /// Creates an error representing a deserialization problem.
163 ///
164 /// Applications should have no need to use this function. The exception
165 /// could be mocks, but this error is too rare to merit mocks. If you are
166 /// writing a mock that extracts values from [wkt::Any], consider using
167 /// `.expect()` calls instead.
168 ///
169 /// # Example
170 /// ```
171 /// use std::error::Error as _;
172 /// use google_cloud_gax::error::Error;
173 /// let error = Error::deser("simulated problem");
174 /// assert!(error.is_deserialization());
175 /// assert!(error.source().is_some());
176 /// ```
177 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
178 pub fn deser<T: Into<BoxError>>(source: T) -> Self {
179 Self {
180 kind: ErrorKind::Deserialization,
181 source: Some(source.into()),
182 }
183 }
184
185 /// The response could not be deserialized.
186 ///
187 /// This is always a client-side generated error. Note that the request may
188 /// or may not have started, and it may or may not complete in the service.
189 /// If the request mutates any state in the service, it may or may not be
190 /// safe to attempt the request again.
191 ///
192 /// # Troubleshooting
193 ///
194 /// The most common cause for deserialization problems are bugs in the
195 /// client library and (rarely) bugs in the service.
196 ///
197 /// When using gRPC services, and if the response includes a [wkt::Any]
198 /// field, the client library may not be able to handle unknown types within
199 /// the `Any`. In all services we know of, this should not happen, but it is
200 /// impossible to prepare the client library for breaking changes in the
201 /// service. Upgrading to the latest version of the client library may be
202 /// the only possible fix.
203 ///
204 /// Beyond this issue with `Any`, while the client libraries are designed to
205 /// handle all valid responses, including unknown fields and unknown
206 /// enumeration values, it is possible that the client library has a bug.
207 /// Please [open an issue] if you run in to this problem. Include any
208 /// instructions on how to reproduce the problem. If you cannot use, or
209 /// prefer not to use, GitHub to discuss this problem, then contact
210 /// [Google Cloud support].
211 ///
212 /// [open an issue]: https://github.com/googleapis/google-cloud-rust/issues/new/choose
213 /// [Google Cloud support]: https://cloud.google.com/support
214 pub fn is_deserialization(&self) -> bool {
215 matches!(self.kind, ErrorKind::Deserialization)
216 }
217
218 /// Not part of the public API, subject to change without notice.
219 ///
220 /// Creates an error representing a serialization problem.
221 ///
222 /// Applications should have no need to use this function. The exception
223 /// could be mocks, but this error is too rare to merit mocks. If you are
224 /// writing a mock that stores values into [wkt::Any], consider using
225 /// `.expect()` calls instead.
226 ///
227 /// # Example
228 /// ```
229 /// use std::error::Error as _;
230 /// use google_cloud_gax::error::Error;
231 /// let error = Error::ser("simulated problem");
232 /// assert!(error.is_serialization());
233 /// assert!(error.source().is_some());
234 /// ```
235 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
236 pub fn ser<T: Into<BoxError>>(source: T) -> Self {
237 Self {
238 kind: ErrorKind::Serialization,
239 source: Some(source.into()),
240 }
241 }
242
243 /// The request could not be serialized.
244 ///
245 /// This is always a client-side generated error, generated before the
246 /// request is made. This error is never transient: the serialization is
247 /// deterministic (modulo out of memory conditions), and will fail on future
248 /// attempts with the same input data.
249 ///
250 /// # Troubleshooting
251 ///
252 /// Most client libraries use HTTP and JSON as the transport, though some
253 /// client libraries use gRPC for some, or all RPCs.
254 ///
255 /// The most common cause for serialization problems is using an unknown
256 /// enum value name with a gRPC-based RPC. gRPC requires integer enum
257 /// values, while JSON accepts both. The client libraries convert **known**
258 /// enum value names to their integer representation, but unknown values
259 /// cannot be sent over gRPC. Verify the enum value is valid, and if so:
260 /// - try using an integer value instead of the enum name, or
261 /// - upgrade the client library: newer versions should include the new
262 /// value.
263 ///
264 /// In all other cases please [open an issue]. While we do not expect these
265 /// problems to be common, we would like to hear if they are so we can
266 /// prevent them. If you cannot use a public issue tracker, contact
267 /// [Google Cloud support].
268 ///
269 /// A less common cause for serialization problems may be an out of memory
270 /// condition, or any other runtime error. Use `format!("{:?}", ...)` to
271 /// examine the error as it should include the original problem.
272 ///
273 /// Finally, sending a [wkt::Any] with a gRPC-based client is unsupported.
274 /// As of this writing, no client libraries sends `Any` via gRPC, but this
275 /// could be a problem in the future.
276 ///
277 /// [open an issue]: https://github.com/googleapis/google-cloud-rust/issues/new/choose
278 /// [Google Cloud support]: https://cloud.google.com/support
279 pub fn is_serialization(&self) -> bool {
280 matches!(self.kind, ErrorKind::Serialization)
281 }
282
283 /// The [Status] payload associated with this error.
284 ///
285 /// # Examples
286 /// ```
287 /// use google_cloud_gax::error::{Error, rpc::{Code, Status}};
288 /// let error = Error::service(Status::default().set_code(Code::NotFound));
289 /// if let Some(status) = error.status() {
290 /// if status.code == Code::NotFound {
291 /// println!("cannot find the thing, more details in {:?}", status.details);
292 /// }
293 /// }
294 /// ```
295 ///
296 /// Google Cloud services return a detailed `Status` message including a
297 /// numeric code for the error type, a human-readable message, and a
298 /// sequence of details which may include localization messages, or more
299 /// information about what caused the failure.
300 ///
301 /// See [AIP-193] for background information about the error model in Google
302 /// Cloud services.
303 ///
304 /// # Troubleshooting
305 ///
306 /// As this error type is typically created by the service, troubleshooting
307 /// this problem typically involves reading the service documentation to
308 /// root cause the problem.
309 ///
310 /// Some services include additional details about the error, sometimes
311 /// including what fields are missing or have bad values in the
312 /// [Status::details] vector. The `std::fmt::Debug` format will include
313 /// such details.
314 ///
315 /// With that said, review the status [Code][crate::error::rpc::Code]
316 /// documentation. The description of the status codes provides a good
317 /// starting point.
318 ///
319 /// [AIP-193]: https://google.aip.dev/193
320 pub fn status(&self) -> Option<&Status> {
321 match &self.kind {
322 ErrorKind::Service(d) => Some(&d.as_ref().status),
323 _ => None,
324 }
325 }
326
327 /// The HTTP status code, if any, associated with this error.
328 ///
329 /// # Example
330 /// ```
331 /// use google_cloud_gax::error::{Error, rpc::{Code, Status}};
332 /// let e = search_for_thing("the thing");
333 /// if let Some(code) = e.http_status_code() {
334 /// if code == 404 {
335 /// println!("cannot find the thing, more details in {e}");
336 /// }
337 /// }
338 ///
339 /// fn search_for_thing(name: &str) -> Error {
340 /// # Error::http(400, http::HeaderMap::new(), bytes::Bytes::from_static(b"NOT FOUND"))
341 /// }
342 /// ```
343 ///
344 /// Sometimes the error is generated before it reaches any Google Cloud
345 /// service. For example, your proxy or the Google load balancers may
346 /// generate errors without the detailed payload described in [AIP-193].
347 /// In such cases the client library returns the status code, headers, and
348 /// http payload.
349 ///
350 /// Note that `http_status_code()`, `http_headers()`, `http_payload()`, and
351 /// `status()` are represented as different fields, because they may be
352 /// set in some errors but not others.
353 ///
354 /// [AIP-193]: https://google.aip.dev/193
355 pub fn http_status_code(&self) -> Option<u16> {
356 match &self.kind {
357 ErrorKind::Transport(d) => d.as_ref().status_code,
358 ErrorKind::Service(d) => d.as_ref().status_code,
359 _ => None,
360 }
361 }
362
363 /// The headers, if any, associated with this error.
364 ///
365 /// # Example
366 /// ```
367 /// use google_cloud_gax::error::{Error, rpc::{Code, Status}};
368 /// let e = search_for_thing("the thing");
369 /// if let Some(headers) = e.http_headers() {
370 /// if let Some(id) = headers.get("x-guploader-uploadid") {
371 /// println!("this can speed up troubleshooting for the Google Cloud Storage support team {id:?}");
372 /// }
373 /// }
374 ///
375 /// fn search_for_thing(name: &str) -> Error {
376 /// # let mut map = http::HeaderMap::new();
377 /// # map.insert("x-guploader-uploadid", http::HeaderValue::from_static("placeholder"));
378 /// # Error::http(400, map, bytes::Bytes::from_static(b"NOT FOUND"))
379 /// }
380 /// ```
381 ///
382 /// Sometimes the error may have headers associated with it. Some services
383 /// include information useful for troubleshooting in the response headers.
384 /// Over gRPC this is called `metadata`, the Google Cloud client libraries
385 /// for Rust normalize this to a [http::HeaderMap].
386 ///
387 /// Many errors do not have this information, e.g. errors detected before
388 /// the request is set, or timeouts. Some RPCs also return "partial"
389 /// errors, which do not include such information.
390 ///
391 /// Note that `http_status_code()`, `http_headers()`, `http_payload()`, and
392 /// `status()` are represented as different fields, because they may be
393 /// set in some errors but not others.
394 pub fn http_headers(&self) -> Option<&http::HeaderMap> {
395 match &self.kind {
396 ErrorKind::Transport(d) => d.as_ref().headers.as_ref(),
397 ErrorKind::Service(d) => d.as_ref().headers.as_ref(),
398 _ => None,
399 }
400 }
401
402 /// The payload, if any, associated with this error.
403 ///
404 /// # Example
405 /// ```
406 /// use google_cloud_gax::error::{Error, rpc::{Code, Status}};
407 /// let e = search_for_thing("the thing");
408 /// if let Some(payload) = e.http_payload() {
409 /// println!("the error included some extra payload {payload:?}");
410 /// }
411 ///
412 /// fn search_for_thing(name: &str) -> Error {
413 /// # Error::http(400, http::HeaderMap::new(), bytes::Bytes::from_static(b"NOT FOUND"))
414 /// }
415 /// ```
416 ///
417 /// Sometimes the error may contain a payload that is useful for
418 /// troubleshooting.
419 ///
420 /// Note that `http_status_code()`, `http_headers()`, `http_payload()`, and
421 /// `status()` are represented as different fields, because they may be
422 /// set in some errors but not others.
423 pub fn http_payload(&self) -> Option<&bytes::Bytes> {
424 match &self.kind {
425 ErrorKind::Transport(d) => d.payload.as_ref(),
426 _ => None,
427 }
428 }
429
430 /// Not part of the public API, subject to change without notice.
431 ///
432 /// Create service errors including transport metadata.
433 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
434 pub fn service_with_http_metadata(
435 status: Status,
436 status_code: Option<u16>,
437 headers: Option<http::HeaderMap>,
438 ) -> Self {
439 let details = ServiceDetails {
440 status_code,
441 headers,
442 status,
443 };
444 let kind = ErrorKind::Service(Box::new(details));
445 Self { kind, source: None }
446 }
447
448 /// Not part of the public API, subject to change without notice.
449 ///
450 /// Cannot find a valid HTTP binding to make the request.
451 ///
452 /// This indicates the request is missing required parameters, or the
453 /// required parameters do not have a valid format.
454 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
455 pub fn binding<T: Into<BoxError>>(source: T) -> Self {
456 Self {
457 kind: ErrorKind::Binding,
458 source: Some(source.into()),
459 }
460 }
461
462 // TODO(#2316) - update the troubleshooting text.
463 /// Not part of the public API, subject to change without notice.
464 ///
465 /// If true, the request was missing required parameters or the parameters
466 /// did not match any of the expected formats.
467 ///
468 /// # Troubleshooting
469 ///
470 /// Typically this indicates a problem in the application. A required field
471 /// in the request builder was not initialized or the format of the field
472 /// does not match the expectations.
473 ///
474 /// We are working to improve the messages in these errors to make them
475 /// self-explanatory, until bug [#2316] is fixed, please consult the service
476 /// REST API documentation.
477 ///
478 /// [#2316]: https://github.com/googleapis/google-cloud-rust/issues/2316
479 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
480 pub fn is_binding(&self) -> bool {
481 matches!(&self.kind, ErrorKind::Binding)
482 }
483
484 /// Not part of the public API, subject to change without notice.
485 ///
486 /// Cannot create the authentication headers.
487 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
488 pub fn authentication(source: CredentialsError) -> Self {
489 Self {
490 kind: ErrorKind::Authentication,
491 source: Some(source.into()),
492 }
493 }
494
495 /// Not part of the public API, subject to change without notice.
496 ///
497 /// Could not create the authentication headers before sending the request.
498 ///
499 /// # Troubleshooting
500 ///
501 /// Typically this indicates a misconfigured authentication environment for
502 /// your application. Very rarely, this may indicate a failure to contact
503 /// the HTTP services used to create [access tokens].
504 ///
505 /// If you are using the default [Credentials], the
506 /// [Authenticate for using client libraries] guide includes good
507 /// information on how to set up your environment for authentication.
508 ///
509 /// If you have configured custom `Credentials`, consult the documentation
510 /// for the specific credential type you used.
511 ///
512 /// [Credentials]: https://docs.rs/google-cloud-auth/latest/google_cloud_auth/credentials/struct.Credentials.html
513 /// [Authenticate for using client libraries]: https://cloud.google.com/docs/authentication/client-libraries
514 /// [access tokens]: https://cloud.google.com/docs/authentication/token-types
515 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
516 pub fn is_authentication(&self) -> bool {
517 matches!(self.kind, ErrorKind::Authentication)
518 }
519
520 /// Not part of the public API, subject to change without notice.
521 ///
522 /// A problem reported by the transport layer.
523 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
524 pub fn http(status_code: u16, headers: HeaderMap, payload: bytes::Bytes) -> Self {
525 let details = TransportDetails {
526 status_code: Some(status_code),
527 headers: Some(headers),
528 payload: Some(payload),
529 };
530 let kind = ErrorKind::Transport(Box::new(details));
531 Self { kind, source: None }
532 }
533
534 /// Not part of the public API, subject to change without notice.
535 ///
536 /// A problem in the transport layer without a full HTTP response.
537 ///
538 /// Examples include: a broken connection after the request is sent, or a
539 /// any HTTP error that did not include a status code or other headers.
540 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
541 pub fn io<T: Into<BoxError>>(source: T) -> Self {
542 let details = TransportDetails {
543 status_code: None,
544 headers: None,
545 payload: None,
546 };
547 Self {
548 kind: ErrorKind::Transport(Box::new(details)),
549 source: Some(source.into()),
550 }
551 }
552
553 /// Not part of the public API, subject to change without notice.
554 ///
555 /// A problem in the transport layer without a full HTTP response.
556 ///
557 /// Examples include read or write problems, and broken connections.
558 ///
559 /// # Troubleshooting
560 ///
561 /// This indicates a problem completing the request. This type of error is
562 /// rare, but includes crashes and restarts on proxies and load balancers.
563 /// It could indicate a bug in the client library, if it tried to use a
564 /// stale connection that had been closed by the service.
565 ///
566 /// Most often, the solution is to use the right retry policy. This may
567 /// involve changing your request to be idempotent, or configuring the
568 /// policy to retry non-idempotent failures.
569 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
570 pub fn is_io(&self) -> bool {
571 matches!(
572 &self.kind,
573 ErrorKind::Transport(d) if matches!(**d, TransportDetails {
574 status_code: None,
575 headers: None,
576 payload: None,
577 ..
578 }))
579 }
580
581 /// Not part of the public API, subject to change without notice.
582 ///
583 /// A problem reported by the transport layer.
584 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
585 pub fn transport<T: Into<BoxError>>(headers: HeaderMap, source: T) -> Self {
586 let details = TransportDetails {
587 headers: Some(headers),
588 status_code: None,
589 payload: None,
590 };
591 Self {
592 kind: ErrorKind::Transport(Box::new(details)),
593 source: Some(source.into()),
594 }
595 }
596
597 /// Not part of the public API, subject to change without notice.
598 ///
599 /// A problem in the transport layer.
600 ///
601 /// Examples include errors in a proxy, load balancer, or other network
602 /// element generated before the service is able to send a full response.
603 ///
604 /// # Troubleshooting
605 ///
606 /// This indicates that the request did not reach the service. Most commonly
607 /// the problem are invalid or mismatched request parameters that route
608 /// the request to the wrong backend.
609 ///
610 /// In this regard, this is similar to the [is_binding][Error::is_binding]
611 /// errors, except that the client library was unable to detect the problem
612 /// locally.
613 ///
614 /// An increasingly common cause for this error is trying to use regional
615 /// resources (e.g. `projects/my-project/locations/us-central1/secrets/my-secret`)
616 /// while using the default, non-regional endpoint. Some services require
617 /// using regional endpoints (e.g.
618 /// `https://secretmanager.us-central1.rep.googleapis.com`) to access such
619 /// resources.
620 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
621 pub fn is_transport(&self) -> bool {
622 matches!(&self.kind, ErrorKind::Transport { .. })
623 }
624
625 /// The error was generated before the RPC started and is transient.
626 pub(crate) fn is_transient_and_before_rpc(&self) -> bool {
627 if !matches!(&self.kind, ErrorKind::Authentication) {
628 return false;
629 }
630 self.source
631 .as_ref()
632 .and_then(|e| e.downcast_ref::<CredentialsError>())
633 .map(|e| e.is_transient())
634 .unwrap_or(false)
635 }
636}
637
638impl std::fmt::Display for Error {
639 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
640 match (&self.kind, &self.source) {
641 (ErrorKind::Binding, Some(e)) => {
642 write!(f, "cannot find a matching binding to send the request: {e}")
643 }
644 (ErrorKind::Serialization, Some(e)) => write!(f, "cannot serialize the request {e}"),
645 (ErrorKind::Deserialization, Some(e)) => {
646 write!(f, "cannot deserialize the response {e}")
647 }
648 (ErrorKind::Authentication, Some(e)) => {
649 write!(f, "cannot create the authentication headers {e}")
650 }
651 (ErrorKind::Timeout, Some(e)) => {
652 write!(f, "the request exceeded the request deadline {e}")
653 }
654 (ErrorKind::Exhausted, Some(e)) => {
655 write!(f, "{e}")
656 }
657 (ErrorKind::Transport(details), _) => details.display(self.source(), f),
658 (ErrorKind::Service(d), _) => {
659 write!(
660 f,
661 "the service reports an error with code {} described as: {}",
662 d.status.code, d.status.message
663 )
664 }
665 (_, None) => unreachable!("no constructor allows this"),
666 }
667 }
668}
669
670impl std::error::Error for Error {
671 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
672 self.source
673 .as_ref()
674 .map(|e| e.as_ref() as &(dyn std::error::Error))
675 }
676}
677
678/// The type of error held by an [Error] instance.
679#[derive(Debug)]
680enum ErrorKind {
681 Binding,
682 Serialization,
683 Deserialization,
684 Authentication,
685 Timeout,
686 Exhausted,
687 Transport(Box<TransportDetails>),
688 Service(Box<ServiceDetails>),
689}
690
691#[derive(Debug)]
692struct TransportDetails {
693 status_code: Option<u16>,
694 headers: Option<HeaderMap>,
695 payload: Option<bytes::Bytes>,
696}
697
698impl TransportDetails {
699 fn display(
700 &self,
701 source: Option<&(dyn StdError + 'static)>,
702 f: &mut std::fmt::Formatter<'_>,
703 ) -> std::fmt::Result {
704 match (source, &self) {
705 (
706 _,
707 TransportDetails {
708 status_code: Some(code),
709 payload: Some(p),
710 ..
711 },
712 ) => {
713 if let Ok(message) = std::str::from_utf8(p.as_ref()) {
714 write!(f, "the HTTP transport reports a [{code}] error: {message}")
715 } else {
716 write!(f, "the HTTP transport reports a [{code}] error: {p:?}")
717 }
718 }
719 (Some(source), _) => {
720 write!(f, "the transport reports an error: {source}")
721 }
722 (None, _) => unreachable!("no Error constructor allows this"),
723 }
724 }
725}
726
727#[derive(Debug)]
728struct ServiceDetails {
729 status_code: Option<u16>,
730 headers: Option<HeaderMap>,
731 status: Status,
732}
733
734#[cfg(test)]
735mod test {
736 use super::*;
737 use crate::error::CredentialsError;
738 use crate::error::rpc::Code;
739 use std::error::Error as StdError;
740
741 #[test]
742 fn service() {
743 let status = Status::default()
744 .set_code(Code::NotFound)
745 .set_message("NOT FOUND");
746 let error = Error::service(status.clone());
747 assert!(error.source().is_none(), "{error:?}");
748 assert_eq!(error.status(), Some(&status));
749 assert!(error.to_string().contains("NOT FOUND"), "{error}");
750 assert!(error.to_string().contains(Code::NotFound.name()), "{error}");
751 assert!(!error.is_transient_and_before_rpc(), "{error:?}");
752 }
753
754 #[test]
755 fn timeout() {
756 let source = wkt::TimestampError::OutOfRange;
757 let error = Error::timeout(source);
758 assert!(error.is_timeout(), "{error:?}");
759 assert!(error.source().is_some(), "{error:?}");
760 let got = error
761 .source()
762 .and_then(|e| e.downcast_ref::<wkt::TimestampError>());
763 assert!(
764 matches!(got, Some(wkt::TimestampError::OutOfRange)),
765 "{error:?}"
766 );
767 let source = wkt::TimestampError::OutOfRange;
768 assert!(error.to_string().contains(&source.to_string()), "{error}");
769 assert!(!error.is_transient_and_before_rpc(), "{error:?}");
770
771 assert!(error.http_headers().is_none(), "{error:?}");
772 assert!(error.http_status_code().is_none(), "{error:?}");
773 assert!(error.http_payload().is_none(), "{error:?}");
774 assert!(error.status().is_none(), "{error:?}");
775 }
776
777 #[test]
778 fn exhausted() {
779 let source = wkt::TimestampError::OutOfRange;
780 let error = Error::exhausted(source);
781 assert!(error.is_exhausted(), "{error:?}");
782 assert!(error.source().is_some(), "{error:?}");
783 let got = error
784 .source()
785 .and_then(|e| e.downcast_ref::<wkt::TimestampError>());
786 assert!(
787 matches!(got, Some(wkt::TimestampError::OutOfRange)),
788 "{error:?}"
789 );
790 let source = wkt::TimestampError::OutOfRange;
791 assert!(error.to_string().contains(&source.to_string()), "{error}");
792 assert!(!error.is_transient_and_before_rpc(), "{error:?}");
793
794 assert!(error.http_headers().is_none(), "{error:?}");
795 assert!(error.http_status_code().is_none(), "{error:?}");
796 assert!(error.http_payload().is_none(), "{error:?}");
797 assert!(error.status().is_none(), "{error:?}");
798 }
799
800 #[test]
801 fn serialization() {
802 let source = wkt::TimestampError::OutOfRange;
803 let error = Error::deser(source);
804 assert!(error.is_deserialization(), "{error:?}");
805 let got = error
806 .source()
807 .and_then(|e| e.downcast_ref::<wkt::TimestampError>());
808 assert!(
809 matches!(got, Some(wkt::TimestampError::OutOfRange)),
810 "{error:?}"
811 );
812 let source = wkt::TimestampError::OutOfRange;
813 assert!(error.to_string().contains(&source.to_string()), "{error}");
814 assert!(!error.is_transient_and_before_rpc(), "{error:?}");
815 }
816
817 #[test]
818 fn service_with_http_metadata() {
819 let status = Status::default()
820 .set_code(Code::NotFound)
821 .set_message("NOT FOUND");
822 let status_code = 404_u16;
823 let headers = {
824 let mut headers = http::HeaderMap::new();
825 headers.insert(
826 "content-type",
827 http::HeaderValue::from_static("application/json"),
828 );
829 headers
830 };
831 let error = Error::service_with_http_metadata(
832 status.clone(),
833 Some(status_code),
834 Some(headers.clone()),
835 );
836 assert_eq!(error.status(), Some(&status));
837 assert!(error.to_string().contains("NOT FOUND"), "{error}");
838 assert!(error.to_string().contains(Code::NotFound.name()), "{error}");
839 assert_eq!(error.http_status_code(), Some(status_code));
840 assert_eq!(error.http_headers(), Some(&headers));
841 assert!(error.http_payload().is_none(), "{error:?}");
842 assert!(!error.is_transient_and_before_rpc(), "{error:?}");
843 }
844
845 #[test]
846 fn binding() {
847 let source = wkt::TimestampError::OutOfRange;
848 let error = Error::binding(source);
849 assert!(error.is_binding(), "{error:?}");
850 assert!(error.source().is_some(), "{error:?}");
851 let got = error
852 .source()
853 .and_then(|e| e.downcast_ref::<wkt::TimestampError>());
854 assert!(
855 matches!(got, Some(wkt::TimestampError::OutOfRange)),
856 "{error:?}"
857 );
858 let source = wkt::TimestampError::OutOfRange;
859 assert!(error.to_string().contains(&source.to_string()), "{error}");
860 assert!(!error.is_transient_and_before_rpc(), "{error:?}");
861
862 assert!(error.status().is_none(), "{error:?}");
863 assert!(error.http_status_code().is_none(), "{error:?}");
864 assert!(error.http_headers().is_none(), "{error:?}");
865 assert!(error.http_payload().is_none(), "{error:?}");
866 }
867
868 #[test]
869 fn ser() {
870 let source = wkt::TimestampError::OutOfRange;
871 let error = Error::ser(source);
872 assert!(error.is_serialization(), "{error:?}");
873 assert!(error.source().is_some(), "{error:?}");
874 let got = error
875 .source()
876 .and_then(|e| e.downcast_ref::<wkt::TimestampError>());
877 assert!(
878 matches!(got, Some(wkt::TimestampError::OutOfRange)),
879 "{error:?}"
880 );
881 let source = wkt::TimestampError::OutOfRange;
882 assert!(error.to_string().contains(&source.to_string()), "{error}");
883 assert!(!error.is_transient_and_before_rpc(), "{error:?}");
884 }
885
886 #[test]
887 fn auth_transient() {
888 let source = CredentialsError::from_msg(true, "test-message");
889 let error = Error::authentication(source);
890 assert!(error.is_authentication(), "{error:?}");
891 assert!(error.source().is_some(), "{error:?}");
892 let got = error
893 .source()
894 .and_then(|e| e.downcast_ref::<CredentialsError>());
895 assert!(matches!(got, Some(c) if c.is_transient()), "{error:?}");
896 assert!(error.to_string().contains("test-message"), "{error}");
897 assert!(error.is_transient_and_before_rpc(), "{error:?}");
898 }
899
900 #[test]
901 fn auth_not_transient() {
902 let source = CredentialsError::from_msg(false, "test-message");
903 let error = Error::authentication(source);
904 assert!(error.is_authentication(), "{error:?}");
905 assert!(error.source().is_some(), "{error:?}");
906 let got = error
907 .source()
908 .and_then(|e| e.downcast_ref::<CredentialsError>());
909 assert!(matches!(got, Some(c) if !c.is_transient()), "{error:?}");
910 assert!(error.to_string().contains("test-message"), "{error}");
911 assert!(!error.is_transient_and_before_rpc(), "{error:?}");
912 }
913
914 #[test]
915 fn http() {
916 let status_code = 404_u16;
917 let headers = {
918 let mut headers = http::HeaderMap::new();
919 headers.insert(
920 "content-type",
921 http::HeaderValue::from_static("application/json"),
922 );
923 headers
924 };
925 let payload = bytes::Bytes::from_static(b"NOT FOUND");
926 let error = Error::http(status_code, headers.clone(), payload.clone());
927 assert!(error.is_transport(), "{error:?}");
928 assert!(!error.is_io(), "{error:?}");
929 assert!(error.source().is_none(), "{error:?}");
930 assert!(error.status().is_none(), "{error:?}");
931 assert!(error.to_string().contains("NOT FOUND"), "{error}");
932 assert!(error.to_string().contains("404"), "{error}");
933 assert_eq!(error.http_status_code(), Some(status_code));
934 assert_eq!(error.http_headers(), Some(&headers));
935 assert_eq!(error.http_payload(), Some(&payload));
936 assert!(!error.is_transient_and_before_rpc(), "{error:?}");
937 }
938
939 #[test]
940 fn http_binary() {
941 let status_code = 404_u16;
942 let headers = {
943 let mut headers = http::HeaderMap::new();
944 headers.insert(
945 "content-type",
946 http::HeaderValue::from_static("application/json"),
947 );
948 headers
949 };
950 let payload = bytes::Bytes::from_static(&[0xFF, 0xFF]);
951 let error = Error::http(status_code, headers.clone(), payload.clone());
952 assert!(error.is_transport(), "{error:?}");
953 assert!(!error.is_io(), "{error:?}");
954 assert!(error.source().is_none(), "{error:?}");
955 assert!(error.status().is_none(), "{error:?}");
956 assert!(
957 error.to_string().contains(&format! {"{payload:?}"}),
958 "{error}"
959 );
960 assert!(error.to_string().contains("404"), "{error}");
961 assert_eq!(error.http_status_code(), Some(status_code));
962 assert_eq!(error.http_headers(), Some(&headers));
963 assert_eq!(error.http_payload(), Some(&payload));
964 assert!(!error.is_transient_and_before_rpc(), "{error:?}");
965 }
966
967 #[test]
968 fn io() {
969 let source = wkt::TimestampError::OutOfRange;
970 let error = Error::io(source);
971 assert!(error.is_transport(), "{error:?}");
972 assert!(error.is_io(), "{error:?}");
973 assert!(error.status().is_none(), "{error:?}");
974 let got = error
975 .source()
976 .and_then(|e| e.downcast_ref::<wkt::TimestampError>());
977 assert!(
978 matches!(got, Some(wkt::TimestampError::OutOfRange)),
979 "{error:?}"
980 );
981 let source = wkt::TimestampError::OutOfRange;
982 assert!(error.to_string().contains(&source.to_string()), "{error}");
983 assert!(!error.is_transient_and_before_rpc(), "{error:?}");
984 }
985
986 #[test]
987 fn transport() {
988 let headers = {
989 let mut headers = http::HeaderMap::new();
990 headers.insert(
991 "content-type",
992 http::HeaderValue::from_static("application/json"),
993 );
994 headers
995 };
996 let source = wkt::TimestampError::OutOfRange;
997 let error = Error::transport(headers.clone(), source);
998 assert!(error.is_transport(), "{error:?}");
999 assert!(!error.is_io(), "{error:?}");
1000 assert!(error.status().is_none(), "{error:?}");
1001 let source = wkt::TimestampError::OutOfRange;
1002 assert!(error.to_string().contains(&source.to_string()), "{error}");
1003 assert!(error.http_status_code().is_none(), "{error:?}");
1004 assert_eq!(error.http_headers(), Some(&headers));
1005 assert!(error.http_payload().is_none(), "{error:?}");
1006 assert!(!error.is_transient_and_before_rpc(), "{error:?}");
1007 }
1008}