## Error

# Struct Error

    pub struct Error { /* private fields */ }

Expand description

The core error returned by all client libraries.

The client libraries report errors from multiple sources. For example, the service may return an error, the transport may be unable to create the necessary connection to make a request, the request may timeout before a response is received, the retry policy may be exhausted, or the library may be unable to format the request due to invalid or missing application application inputs.

Most applications will just return the error or log it, without any further action. However, some applications may need to interrogate the error details. This type offers a series of predicates to determine the error kind. The type also offers accessors to query the most common error details. Applications can query the error source for deeper information.

## §Example

    use google_cloud_gax::error::Error;
    match example_function() {
        Err(e) if matches!(e.status(), Some(_)) => {
            println!("service error {e}, debug using {:?}", e.status().unwrap());
        },
        Err(e) if e.is_timeout() => { println!("not enough time {e}"); },
        Err(e) => { println!("some other error {e}"); },
        Ok(_) => { println!("success, how boring"); },
    }

    fn example_function() -> Result<String, Error> {
        // ... details omitted ...
    }

## Implementations§

§

### impl Error

#### pub fn service(status: Status) -> Error

Creates an error with the information returned by Google Cloud services.

##### §Example

    use google_cloud_gax::error::Error;
    use google_cloud_gax::error::rpc::{Code, Status};
    let status = Status::default().set_code(Code::NotFound).set_message("NOT FOUND");
    let error = Error::service(status.clone());
    assert_eq!(error.status(), Some(&status));

#### pub fn timeout<T>(source: T) -> Error
where T: Into<Box<dyn Error + Sync + Send>>,

Creates an error representing a timeout.

##### §Example

    use std::error::Error as _;
    use google_cloud_gax::error::Error;
    let error = Error::timeout("simulated timeout");
    assert!(error.is_timeout());
    assert!(error.source().is_some());

#### pub fn is_timeout(&self) -> bool

The request could not be completed before its deadline.

This is always a client-side generated error. Note that the request may or may not have started, and it may or may not complete in the service. If the request mutates any state in the service, it may or may not be safe to attempt the request again.

##### §Troubleshooting

The most common cause of this problem is setting a timeout value that is based on the observed latency when the service is not under load. Consider increasing the timeout value to handle temporary latency increases too.

It could also indicate a congestion in the network, a service outage, or a service that is under load and will take time to scale up.

#### pub fn exhausted<T>(source: T) -> Error
where T: Into<Box<dyn Error + Sync + Send>>,

Creates an error representing an exhausted policy.

##### §Example

    use std::error::Error as _;
    use google_cloud_gax::error::Error;
    let error = Error::exhausted("too many retry attempts");
    assert!(error.is_exhausted());
    assert!(error.source().is_some());

#### pub fn is_exhausted(&self) -> bool

The request could not complete be before the retry policy expired.

This is always a client-side generated error, but it may be the result of multiple errors received from the service.

##### §Troubleshooting

The most common cause of this problem is a transient problem that lasts longer than your retry policy. For example, your retry policy may effectively be exhausted after a few seconds, but some services may take minutes to recover.

If your application can tolerate longer recovery times then extend the retry policy. Otherwise consider recovery at a higher level, such as seeking human intervention, switching the workload to a different location, failing the batch job and starting from a previous checkpoint, or even presenting an error to the application user.

#### pub fn is_deserialization(&self) -> bool

The response could not be deserialized.

This is always a client-side generated error. Note that the request may or may not have started, and it may or may not complete in the service. If the request mutates any state in the service, it may or may not be safe to attempt the request again.

##### §Troubleshooting

The most common cause for deserialization problems are bugs in the client library and (rarely) bugs in the service.

When using gRPC services, and if the response includes a [wkt::Any] field, the client library may not be able to handle unknown types within the `Any`. In all services we know of, this should not happen, but it is impossible to prepare the client library for breaking changes in the service. Upgrading to the latest version of the client library may be the only possible fix.

Beyond this issue with `Any`, while the client libraries are designed to handle all valid responses, including unknown fields and unknown enumeration values, it is possible that the client library has a bug. Please open an issue if you run in to this problem. Include any instructions on how to reproduce the problem. If you cannot use, or prefer not to use, GitHub to discuss this problem, then contact Google Cloud support.

#### pub fn is_serialization(&self) -> bool

The request could not be serialized.

This is always a client-side generated error, generated before the request is made. This error is never transient: the serialization is deterministic (modulo out of memory conditions), and will fail on future attempts with the same input data.

##### §Troubleshooting

Most client libraries use HTTP and JSON as the transport, though some client libraries use gRPC for some, or all RPCs.

The most common cause for serialization problems is using an unknown enum value name with a gRPC-based RPC. gRPC requires integer enum values, while JSON accepts both. The client libraries convert known enum value names to their integer representation, but unknown values cannot be sent over gRPC. Verify the enum value is valid, and if so:

- try using an integer value instead of the enum name, or
- upgrade the client library: newer versions should include the new value.

In all other cases please open an issue. While we do not expect these problems to be common, we would like to hear if they are so we can prevent them. If you cannot use a public issue tracker, contact Google Cloud support.

A less common cause for serialization problems may be an out of memory condition, or any other runtime error. Use `format!("{:?}", ...)` to examine the error as it should include the original problem.

Finally, sending a [wkt::Any] with a gRPC-based client is unsupported. As of this writing, no client libraries sends `Any` via gRPC, but this could be a problem in the future.

#### pub fn status(&self) -> Option<&Status>

The [Status] payload associated with this error.

##### §Examples

    use google_cloud_gax::error::{Error, rpc::{Code, Status}};
    let error = Error::service(Status::default().set_code(Code::NotFound));
    if let Some(status) = error.status() {
        if status.code == Code::NotFound {
            println!("cannot find the thing, more details in {:?}", status.details);
        }
    }

Google Cloud services return a detailed `Status` message including a numeric code for the error type, a human-readable message, and a sequence of details which may include localization messages, or more information about what caused the failure.

See AIP-193 for background information about the error model in Google Cloud services.

##### §Troubleshooting

As this error type is typically created by the service, troubleshooting this problem typically involves reading the service documentation to root cause the problem.

Some services include additional details about the error, sometimes including what fields are missing or have bad values in the [Status::details] vector. The `std::fmt::Debug` format will include such details.

With that said, review the status [Code][crate::error::rpc::Code] documentation. The description of the status codes provides a good starting point.

#### pub fn http_status_code(&self) -> Option<u16>

The HTTP status code, if any, associated with this error.

##### §Example

    use google_cloud_gax::error::{Error, rpc::{Code, Status}};
    let e = search_for_thing("the thing");
    if let Some(code) = e.http_status_code() {
        if code == 404 {
            println!("cannot find the thing, more details in {e}");
        }
    }

    fn search_for_thing(name: &str) -> Error {
    }

Sometimes the error is generated before it reaches any Google Cloud service. For example, your proxy or the Google load balancers may generate errors without the detailed payload described in AIP-193. In such cases the client library returns the status code, headers, and http payload.

Note that `http_status_code()`, `http_headers()`, `http_payload()`, and `status()` are represented as different fields, because they may be set in some errors but not others.

#### pub fn http_headers(&self) -> Option<&HeaderMap>

The headers, if any, associated with this error.

##### §Example

    use google_cloud_gax::error::{Error, rpc::{Code, Status}};
    let e = search_for_thing("the thing");
    if let Some(headers) = e.http_headers() {
        if let Some(id) = headers.get("x-guploader-uploadid") {
            println!("this can speed up troubleshooting for the Google Cloud Storage support team {id:?}");
        }
    }

    fn search_for_thing(name: &str) -> Error {
    }

Sometimes the error may have headers associated with it. Some services include information useful for troubleshooting in the response headers. Over gRPC this is called `metadata`, the Google Cloud client libraries for Rust normalize this to a [http::HeaderMap].

Many errors do not have this information, e.g. errors detected before the request is set, or timeouts. Some RPCs also return “partial” errors, which do not include such information.

Note that `http_status_code()`, `http_headers()`, `http_payload()`, and `status()` are represented as different fields, because they may be set in some errors but not others.

#### pub fn http_payload(&self) -> Option<&Bytes>

The payload, if any, associated with this error.

##### §Example

    use google_cloud_gax::error::{Error, rpc::{Code, Status}};
    let e = search_for_thing("the thing");
    if let Some(payload) = e.http_payload() {
       println!("the error included some extra payload {payload:?}");
    }

    fn search_for_thing(name: &str) -> Error {
    }

Sometimes the error may contain a payload that is useful for troubleshooting.

Note that `http_status_code()`, `http_headers()`, `http_payload()`, and `status()` are represented as different fields, because they may be set in some errors but not others.

## Trait Implementations§

§

### impl Debug for Error

§

#### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

### impl Display for Error

§

#### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

### impl Error for Error

§

#### fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

#### fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Read more
1.0.0 · Source§

#### fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

#### fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (`error_generic_member_access`)
Provides type-based access to context intended for error reports. Read more

## Auto Trait Implementations§

§

### impl Freeze for Error

§

### impl !RefUnwindSafe for Error

§

### impl Send for Error

§

### impl Sync for Error

§

### impl Unpin for Error

§

### impl !UnwindSafe for Error

## Blanket Implementations§

Source§

### impl<T> Any for T
where T: 'static + ?Sized,

Source§

#### fn type_id(&self) -> TypeId

Gets the `TypeId` of `self`. Read more
Source§

### impl<T> Borrow<T> for T
where T: ?Sized,

Source§

#### fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

### impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

#### fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

### impl<T> From<T> for T

Source§

#### fn from(t: T) -> T

Returns the argument unchanged.

§

### impl<T> Instrument for T

§

#### fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [`Span`], returning an `Instrumented` wrapper. Read more
§

#### fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more
Source§

### impl<T, U> Into<U> for T
where U: From<T>,

Source§

#### fn into(self) -> U

Calls `U::from(self)`.

That is, this conversion is whatever the implementation of `From<T> for U` chooses to do.

§

### impl<T> IntoRequest<T> for T

§

#### fn into_request(self) -> Request<T>

Wrap the input message `T` in a `tonic::Request`
§

### impl<L> LayerExt<L> for L

§

#### fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in [`Layered`].
§

### impl<T> PolicyExt for T
where T: ?Sized,

§

#### fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new `Policy` that returns [`Action::Follow`] only if `self` and `other` return `Action::Follow`. Read more
§

#### fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new `Policy` that returns [`Action::Follow`] if either `self` or `other` returns `Action::Follow`. Read more
Source§

### impl<T> ToString for T
where T: Display + ?Sized,

Source§

#### fn to_string(&self) -> String

Converts the given value to a `String`. Read more
§

### impl<T> ToStringFallible for T
where T: Display,

§

#### fn try_to_string(&self) -> Result<String, TryReserveError>

`ToString::to_string`, but without panic on OOM.

Source§

### impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

#### type Error = Infallible

The type returned in the event of a conversion error.
Source§

#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

### impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

#### type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

### impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

#### fn vzip(self) -> V

§

### impl<T> WithSubscriber for T

§

#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided `Subscriber` to this type, returning a [`WithDispatch`] wrapper. Read more
§

#### fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default `Subscriber` to this type, returning a [`WithDispatch`] wrapper. Read more