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 Self::service_full(status, status_code, headers, None)
440 }
441
442 /// Not part of the public API, subject to change without notice.
443 ///
444 /// Create service errors including transport metadata.
445 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
446 pub fn service_full(
447 status: Status,
448 status_code: Option<u16>,
449 headers: Option<http::HeaderMap>,
450 source: Option<BoxError>,
451 ) -> Self {
452 let details = ServiceDetails {
453 status_code,
454 headers,
455 status,
456 };
457 let kind = ErrorKind::Service(Box::new(details));
458 Self { kind, source }
459 }
460
461 /// Not part of the public API, subject to change without notice.
462 ///
463 /// Cannot find a valid HTTP binding to make the request.
464 ///
465 /// This indicates the request is missing required parameters, or the
466 /// required parameters do not have a valid format.
467 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
468 pub fn binding<T: Into<BoxError>>(source: T) -> Self {
469 Self {
470 kind: ErrorKind::Binding,
471 source: Some(source.into()),
472 }
473 }
474
475 /// Not part of the public API, subject to change without notice.
476 ///
477 /// If true, the request was missing required parameters or the parameters
478 /// did not match any of the expected formats.
479 ///
480 /// # Troubleshooting
481 ///
482 /// Typically this indicates a problem in the application. A required field
483 /// in the request builder was not initialized, or the format of the field
484 /// does not match the expectations to make a successful request.
485 ///
486 /// When printed out in debug format the error indicates what formats and
487 /// fields to use.
488 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
489 pub fn is_binding(&self) -> bool {
490 matches!(&self.kind, ErrorKind::Binding)
491 }
492
493 /// Not part of the public API, subject to change without notice.
494 ///
495 /// Cannot create the authentication headers.
496 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
497 pub fn authentication(source: CredentialsError) -> Self {
498 Self {
499 kind: ErrorKind::Authentication,
500 source: Some(source.into()),
501 }
502 }
503
504 /// Not part of the public API, subject to change without notice.
505 ///
506 /// Could not create the authentication headers before sending the request.
507 ///
508 /// # Troubleshooting
509 ///
510 /// Typically this indicates a misconfigured authentication environment for
511 /// your application. Very rarely, this may indicate a failure to contact
512 /// the HTTP services used to create [access tokens].
513 ///
514 /// If you are using the default [Credentials], the
515 /// [Authenticate for using client libraries] guide includes good
516 /// information on how to set up your environment for authentication.
517 ///
518 /// If you have configured custom `Credentials`, consult the documentation
519 /// for the specific credential type you used.
520 ///
521 /// [Credentials]: https://docs.rs/google-cloud-auth/latest/google_cloud_auth/credentials/struct.Credentials.html
522 /// [Authenticate for using client libraries]: https://cloud.google.com/docs/authentication/client-libraries
523 /// [access tokens]: https://cloud.google.com/docs/authentication/token-types
524 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
525 pub fn is_authentication(&self) -> bool {
526 matches!(self.kind, ErrorKind::Authentication)
527 }
528
529 /// Not part of the public API, subject to change without notice.
530 ///
531 /// A problem reported by the transport layer.
532 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
533 pub fn http(status_code: u16, headers: HeaderMap, payload: bytes::Bytes) -> Self {
534 let details = TransportDetails {
535 status_code: Some(status_code),
536 headers: Some(headers),
537 payload: Some(payload),
538 };
539 let kind = ErrorKind::Transport(Box::new(details));
540 Self { kind, source: None }
541 }
542
543 /// Not part of the public API, subject to change without notice.
544 ///
545 /// A problem in the transport layer without a full HTTP response.
546 ///
547 /// Examples include: a broken connection after the request is sent, or a
548 /// any HTTP error that did not include a status code or other headers.
549 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
550 pub fn io<T: Into<BoxError>>(source: T) -> Self {
551 let details = TransportDetails {
552 status_code: None,
553 headers: None,
554 payload: None,
555 };
556 Self {
557 kind: ErrorKind::Transport(Box::new(details)),
558 source: Some(source.into()),
559 }
560 }
561
562 /// Not part of the public API, subject to change without notice.
563 ///
564 /// A problem in the transport layer without a full HTTP response.
565 ///
566 /// Examples include read or write problems, and broken connections.
567 ///
568 /// # Troubleshooting
569 ///
570 /// This indicates a problem completing the request. This type of error is
571 /// rare, but includes crashes and restarts on proxies and load balancers.
572 /// It could indicate a bug in the client library, if it tried to use a
573 /// stale connection that had been closed by the service.
574 ///
575 /// Most often, the solution is to use the right retry policy. This may
576 /// involve changing your request to be idempotent, or configuring the
577 /// policy to retry non-idempotent failures.
578 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
579 pub fn is_io(&self) -> bool {
580 matches!(
581 &self.kind,
582 ErrorKind::Transport(d) if matches!(**d, TransportDetails {
583 status_code: None,
584 headers: None,
585 payload: None,
586 ..
587 }))
588 }
589
590 /// Not part of the public API, subject to change without notice.
591 ///
592 /// A problem connecting with the endpoint.
593 ///
594 /// Examples include DNS errors and broken connections.
595 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
596 pub fn connect<T: Into<BoxError>>(source: T) -> Self {
597 Self {
598 kind: ErrorKind::Connect,
599 source: Some(source.into()),
600 }
601 }
602
603 /// Not part of the public API, subject to change without notice.
604 ///
605 /// A problem connecting with the endpoint.
606 ///
607 /// Examples include DNS errors and broken connections.
608 ///
609 /// # Troubleshooting
610 ///
611 /// This indicates a problem starting the request. It always occurs before a
612 /// request is made, so it is always safe to retry, even if the request is
613 /// not idempotent. However, retrying does not indicate the request will
614 /// ever succeed (e.g. if a network is permanently down).
615 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
616 pub fn is_connect(&self) -> bool {
617 matches!(&self.kind, ErrorKind::Connect)
618 }
619
620 /// Not part of the public API, subject to change without notice.
621 ///
622 /// A problem reported by the transport layer.
623 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
624 pub fn transport<T: Into<BoxError>>(headers: HeaderMap, source: T) -> Self {
625 let details = TransportDetails {
626 headers: Some(headers),
627 status_code: None,
628 payload: None,
629 };
630 Self {
631 kind: ErrorKind::Transport(Box::new(details)),
632 source: Some(source.into()),
633 }
634 }
635
636 /// Not part of the public API, subject to change without notice.
637 ///
638 /// A problem in the transport layer.
639 ///
640 /// Examples include errors in a proxy, load balancer, or other network
641 /// element generated before the service is able to send a full response.
642 ///
643 /// # Troubleshooting
644 ///
645 /// This indicates that the request did not reach the service. Most commonly
646 /// the problem are invalid or mismatched request parameters that route
647 /// the request to the wrong backend.
648 ///
649 /// In this regard, this is similar to the [is_binding][Error::is_binding]
650 /// errors, except that the client library was unable to detect the problem
651 /// locally.
652 ///
653 /// An increasingly common cause for this error is trying to use regional
654 /// resources (e.g. `projects/my-project/locations/us-central1/secrets/my-secret`)
655 /// while using the default, non-regional endpoint. Some services require
656 /// using regional endpoints (e.g.
657 /// `https://secretmanager.us-central1.rep.googleapis.com`) to access such
658 /// resources.
659 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
660 pub fn is_transport(&self) -> bool {
661 matches!(&self.kind, ErrorKind::Transport { .. })
662 }
663
664 /// The error was generated before the RPC started and is transient.
665 #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
666 pub fn is_transient_and_before_rpc(&self) -> bool {
667 match &self.kind {
668 ErrorKind::Connect => true,
669 ErrorKind::Authentication => self
670 .source
671 .as_ref()
672 .and_then(|e| e.downcast_ref::<CredentialsError>())
673 .map(|e| e.is_transient())
674 .unwrap_or(false),
675 _ => false,
676 }
677 }
678}
679
680impl std::fmt::Display for Error {
681 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
682 match (&self.kind, &self.source) {
683 (ErrorKind::Binding, Some(e)) => {
684 write!(f, "cannot find a matching binding to send the request: {e}")
685 }
686 (ErrorKind::Serialization, Some(e)) => write!(f, "cannot serialize the request {e}"),
687 (ErrorKind::Deserialization, Some(e)) => {
688 write!(f, "cannot deserialize the response {e}")
689 }
690 (ErrorKind::Authentication, Some(e)) => {
691 write!(f, "cannot create the authentication headers {e}")
692 }
693 (ErrorKind::Timeout, Some(e)) => {
694 write!(f, "the request exceeded the request deadline {e}")
695 }
696 (ErrorKind::Exhausted, Some(e)) => {
697 write!(f, "{e}")
698 }
699 (ErrorKind::Connect, Some(e)) => {
700 write!(f, "cannot connect to endpoint: {e}")
701 }
702 (ErrorKind::Transport(details), _) => details.display(self.source(), f),
703 (ErrorKind::Service(d), _) => {
704 write!(
705 f,
706 "the service reports an error with code {} described as: {}",
707 d.status.code, d.status.message
708 )
709 }
710 (_, None) => unreachable!("no constructor allows this"),
711 }
712 }
713}
714
715impl std::error::Error for Error {
716 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
717 self.source
718 .as_ref()
719 .map(|e| e.as_ref() as &dyn std::error::Error)
720 }
721}
722
723/// The type of error held by an [Error] instance.
724#[derive(Debug)]
725enum ErrorKind {
726 Binding,
727 Serialization,
728 Deserialization,
729 Authentication,
730 Timeout,
731 Exhausted,
732 Connect,
733 Transport(Box<TransportDetails>),
734 Service(Box<ServiceDetails>),
735}
736
737#[derive(Debug)]
738struct TransportDetails {
739 status_code: Option<u16>,
740 headers: Option<HeaderMap>,
741 payload: Option<bytes::Bytes>,
742}
743
744impl TransportDetails {
745 fn display(
746 &self,
747 source: Option<&(dyn StdError + 'static)>,
748 f: &mut std::fmt::Formatter<'_>,
749 ) -> std::fmt::Result {
750 match (source, &self) {
751 (
752 _,
753 TransportDetails {
754 status_code: Some(code),
755 payload: Some(p),
756 ..
757 },
758 ) => {
759 if let Ok(message) = std::str::from_utf8(p.as_ref()) {
760 write!(f, "the HTTP transport reports a [{code}] error: {message}")
761 } else {
762 write!(f, "the HTTP transport reports a [{code}] error: {p:?}")
763 }
764 }
765 (Some(source), _) => {
766 write!(f, "the transport reports an error: {source}")
767 }
768 (None, _) => unreachable!("no Error constructor allows this"),
769 }
770 }
771}
772
773#[derive(Debug)]
774struct ServiceDetails {
775 status_code: Option<u16>,
776 headers: Option<HeaderMap>,
777 status: Status,
778}
779
780#[cfg(test)]
781mod tests {
782 use super::*;
783 use crate::error::CredentialsError;
784 use crate::error::rpc::Code;
785 use std::error::Error as StdError;
786
787 #[test]
788 fn service() {
789 let status = Status::default()
790 .set_code(Code::NotFound)
791 .set_message("NOT FOUND");
792 let error = Error::service(status.clone());
793 assert!(error.source().is_none(), "{error:?}");
794 assert_eq!(error.status(), Some(&status));
795 assert!(error.to_string().contains("NOT FOUND"), "{error}");
796 assert!(error.to_string().contains(Code::NotFound.name()), "{error}");
797 assert!(!error.is_transient_and_before_rpc(), "{error:?}");
798 }
799
800 #[test]
801 fn timeout() {
802 let source = wkt::TimestampError::OutOfRange;
803 let error = Error::timeout(source);
804 assert!(error.is_timeout(), "{error:?}");
805 assert!(error.source().is_some(), "{error:?}");
806 let got = error
807 .source()
808 .and_then(|e| e.downcast_ref::<wkt::TimestampError>());
809 assert!(
810 matches!(got, Some(wkt::TimestampError::OutOfRange)),
811 "{error:?}"
812 );
813 let source = wkt::TimestampError::OutOfRange;
814 assert!(error.to_string().contains(&source.to_string()), "{error}");
815 assert!(!error.is_transient_and_before_rpc(), "{error:?}");
816
817 assert!(error.http_headers().is_none(), "{error:?}");
818 assert!(error.http_status_code().is_none(), "{error:?}");
819 assert!(error.http_payload().is_none(), "{error:?}");
820 assert!(error.status().is_none(), "{error:?}");
821 }
822
823 #[test]
824 fn exhausted() {
825 let source = wkt::TimestampError::OutOfRange;
826 let error = Error::exhausted(source);
827 assert!(error.is_exhausted(), "{error:?}");
828 assert!(error.source().is_some(), "{error:?}");
829 let got = error
830 .source()
831 .and_then(|e| e.downcast_ref::<wkt::TimestampError>());
832 assert!(
833 matches!(got, Some(wkt::TimestampError::OutOfRange)),
834 "{error:?}"
835 );
836 let source = wkt::TimestampError::OutOfRange;
837 assert!(error.to_string().contains(&source.to_string()), "{error}");
838 assert!(!error.is_transient_and_before_rpc(), "{error:?}");
839
840 assert!(error.http_headers().is_none(), "{error:?}");
841 assert!(error.http_status_code().is_none(), "{error:?}");
842 assert!(error.http_payload().is_none(), "{error:?}");
843 assert!(error.status().is_none(), "{error:?}");
844 }
845
846 #[test]
847 fn serialization() {
848 let source = wkt::TimestampError::OutOfRange;
849 let error = Error::deser(source);
850 assert!(error.is_deserialization(), "{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
863 #[test]
864 fn connect() {
865 let source = wkt::TimestampError::OutOfRange;
866 let error = Error::connect(source);
867 assert!(error.is_connect(), "{error:?}");
868 assert!(error.source().is_some(), "{error:?}");
869 let got = error
870 .source()
871 .and_then(|e| e.downcast_ref::<wkt::TimestampError>());
872 assert!(
873 matches!(got, Some(wkt::TimestampError::OutOfRange)),
874 "{error:?}"
875 );
876 let source = wkt::TimestampError::OutOfRange;
877 assert!(error.to_string().contains(&source.to_string()), "{error}");
878 assert!(error.is_transient_and_before_rpc(), "{error:?}");
879
880 assert!(error.http_headers().is_none(), "{error:?}");
881 assert!(error.http_status_code().is_none(), "{error:?}");
882 assert!(error.http_payload().is_none(), "{error:?}");
883 assert!(error.status().is_none(), "{error:?}");
884 }
885
886 #[test]
887 fn service_with_http_metadata() {
888 let status = Status::default()
889 .set_code(Code::NotFound)
890 .set_message("NOT FOUND");
891 let status_code = 404_u16;
892 let headers = {
893 let mut headers = http::HeaderMap::new();
894 headers.insert(
895 "content-type",
896 http::HeaderValue::from_static("application/json"),
897 );
898 headers
899 };
900 let error = Error::service_with_http_metadata(
901 status.clone(),
902 Some(status_code),
903 Some(headers.clone()),
904 );
905 assert_eq!(error.status(), Some(&status));
906 assert!(error.to_string().contains("NOT FOUND"), "{error}");
907 assert!(error.to_string().contains(Code::NotFound.name()), "{error}");
908 assert_eq!(error.http_status_code(), Some(status_code));
909 assert_eq!(error.http_headers(), Some(&headers));
910 assert!(error.http_payload().is_none(), "{error:?}");
911 assert!(!error.is_transient_and_before_rpc(), "{error:?}");
912 }
913
914 #[test]
915 fn service_full() {
916 let status = Status::default()
917 .set_code(Code::NotFound)
918 .set_message("NOT FOUND");
919 let status_code = 404_u16;
920 let headers = {
921 let mut headers = http::HeaderMap::new();
922 headers.insert(
923 "content-type",
924 http::HeaderValue::from_static("application/json"),
925 );
926 headers
927 };
928 let error = Error::service_full(
929 status.clone(),
930 Some(status_code),
931 Some(headers.clone()),
932 Some(Box::new(wkt::TimestampError::OutOfRange)),
933 );
934 assert_eq!(error.status(), Some(&status));
935 assert!(error.to_string().contains("NOT FOUND"), "{error}");
936 assert!(error.to_string().contains(Code::NotFound.name()), "{error}");
937 assert_eq!(error.http_status_code(), Some(status_code));
938 assert_eq!(error.http_headers(), Some(&headers));
939 assert!(error.http_payload().is_none(), "{error:?}");
940 assert!(!error.is_transient_and_before_rpc(), "{error:?}");
941 assert!(error.source().is_some(), "{error:?}");
942 let got = error
943 .source()
944 .and_then(|e| e.downcast_ref::<wkt::TimestampError>());
945 assert!(
946 matches!(got, Some(wkt::TimestampError::OutOfRange)),
947 "{error:?}"
948 );
949 }
950
951 #[test]
952 fn binding() {
953 let source = wkt::TimestampError::OutOfRange;
954 let error = Error::binding(source);
955 assert!(error.is_binding(), "{error:?}");
956 assert!(error.source().is_some(), "{error:?}");
957 let got = error
958 .source()
959 .and_then(|e| e.downcast_ref::<wkt::TimestampError>());
960 assert!(
961 matches!(got, Some(wkt::TimestampError::OutOfRange)),
962 "{error:?}"
963 );
964 let source = wkt::TimestampError::OutOfRange;
965 assert!(error.to_string().contains(&source.to_string()), "{error}");
966 assert!(!error.is_transient_and_before_rpc(), "{error:?}");
967
968 assert!(error.status().is_none(), "{error:?}");
969 assert!(error.http_status_code().is_none(), "{error:?}");
970 assert!(error.http_headers().is_none(), "{error:?}");
971 assert!(error.http_payload().is_none(), "{error:?}");
972 }
973
974 #[test]
975 fn ser() {
976 let source = wkt::TimestampError::OutOfRange;
977 let error = Error::ser(source);
978 assert!(error.is_serialization(), "{error:?}");
979 assert!(error.source().is_some(), "{error:?}");
980 let got = error
981 .source()
982 .and_then(|e| e.downcast_ref::<wkt::TimestampError>());
983 assert!(
984 matches!(got, Some(wkt::TimestampError::OutOfRange)),
985 "{error:?}"
986 );
987 let source = wkt::TimestampError::OutOfRange;
988 assert!(error.to_string().contains(&source.to_string()), "{error}");
989 assert!(!error.is_transient_and_before_rpc(), "{error:?}");
990 }
991
992 #[test]
993 fn auth_transient() {
994 let source = CredentialsError::from_msg(true, "test-message");
995 let error = Error::authentication(source);
996 assert!(error.is_authentication(), "{error:?}");
997 assert!(error.source().is_some(), "{error:?}");
998 let got = error
999 .source()
1000 .and_then(|e| e.downcast_ref::<CredentialsError>());
1001 assert!(matches!(got, Some(c) if c.is_transient()), "{error:?}");
1002 assert!(error.to_string().contains("test-message"), "{error}");
1003 assert!(error.is_transient_and_before_rpc(), "{error:?}");
1004 }
1005
1006 #[test]
1007 fn auth_not_transient() {
1008 let source = CredentialsError::from_msg(false, "test-message");
1009 let error = Error::authentication(source);
1010 assert!(error.is_authentication(), "{error:?}");
1011 assert!(error.source().is_some(), "{error:?}");
1012 let got = error
1013 .source()
1014 .and_then(|e| e.downcast_ref::<CredentialsError>());
1015 assert!(matches!(got, Some(c) if !c.is_transient()), "{error:?}");
1016 assert!(error.to_string().contains("test-message"), "{error}");
1017 assert!(!error.is_transient_and_before_rpc(), "{error:?}");
1018 }
1019
1020 #[test]
1021 fn http() {
1022 let status_code = 404_u16;
1023 let headers = {
1024 let mut headers = http::HeaderMap::new();
1025 headers.insert(
1026 "content-type",
1027 http::HeaderValue::from_static("application/json"),
1028 );
1029 headers
1030 };
1031 let payload = bytes::Bytes::from_static(b"NOT FOUND");
1032 let error = Error::http(status_code, headers.clone(), payload.clone());
1033 assert!(error.is_transport(), "{error:?}");
1034 assert!(!error.is_io(), "{error:?}");
1035 assert!(error.source().is_none(), "{error:?}");
1036 assert!(error.status().is_none(), "{error:?}");
1037 assert!(error.to_string().contains("NOT FOUND"), "{error}");
1038 assert!(error.to_string().contains("404"), "{error}");
1039 assert_eq!(error.http_status_code(), Some(status_code));
1040 assert_eq!(error.http_headers(), Some(&headers));
1041 assert_eq!(error.http_payload(), Some(&payload));
1042 assert!(!error.is_transient_and_before_rpc(), "{error:?}");
1043 }
1044
1045 #[test]
1046 fn http_binary() {
1047 let status_code = 404_u16;
1048 let headers = {
1049 let mut headers = http::HeaderMap::new();
1050 headers.insert(
1051 "content-type",
1052 http::HeaderValue::from_static("application/json"),
1053 );
1054 headers
1055 };
1056 let payload = bytes::Bytes::from_static(&[0xFF, 0xFF]);
1057 let error = Error::http(status_code, headers.clone(), payload.clone());
1058 assert!(error.is_transport(), "{error:?}");
1059 assert!(!error.is_io(), "{error:?}");
1060 assert!(error.source().is_none(), "{error:?}");
1061 assert!(error.status().is_none(), "{error:?}");
1062 assert!(
1063 error.to_string().contains(&format! {"{payload:?}"}),
1064 "{error}"
1065 );
1066 assert!(error.to_string().contains("404"), "{error}");
1067 assert_eq!(error.http_status_code(), Some(status_code));
1068 assert_eq!(error.http_headers(), Some(&headers));
1069 assert_eq!(error.http_payload(), Some(&payload));
1070 assert!(!error.is_transient_and_before_rpc(), "{error:?}");
1071 }
1072
1073 #[test]
1074 fn io() {
1075 let source = wkt::TimestampError::OutOfRange;
1076 let error = Error::io(source);
1077 assert!(error.is_transport(), "{error:?}");
1078 assert!(error.is_io(), "{error:?}");
1079 assert!(error.status().is_none(), "{error:?}");
1080 let got = error
1081 .source()
1082 .and_then(|e| e.downcast_ref::<wkt::TimestampError>());
1083 assert!(
1084 matches!(got, Some(wkt::TimestampError::OutOfRange)),
1085 "{error:?}"
1086 );
1087 let source = wkt::TimestampError::OutOfRange;
1088 assert!(error.to_string().contains(&source.to_string()), "{error}");
1089 assert!(!error.is_transient_and_before_rpc(), "{error:?}");
1090 }
1091
1092 #[test]
1093 fn transport() {
1094 let headers = {
1095 let mut headers = http::HeaderMap::new();
1096 headers.insert(
1097 "content-type",
1098 http::HeaderValue::from_static("application/json"),
1099 );
1100 headers
1101 };
1102 let source = wkt::TimestampError::OutOfRange;
1103 let error = Error::transport(headers.clone(), source);
1104 assert!(error.is_transport(), "{error:?}");
1105 assert!(!error.is_io(), "{error:?}");
1106 assert!(error.status().is_none(), "{error:?}");
1107 let source = wkt::TimestampError::OutOfRange;
1108 assert!(error.to_string().contains(&source.to_string()), "{error}");
1109 assert!(error.http_status_code().is_none(), "{error:?}");
1110 assert_eq!(error.http_headers(), Some(&headers));
1111 assert!(error.http_payload().is_none(), "{error:?}");
1112 assert!(!error.is_transient_and_before_rpc(), "{error:?}");
1113 }
1114}