Skip to main content

google_cloud_spanner/
error.rs

1// Copyright 2026 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 crate::Error;
16use google_cloud_gax::error::rpc::{Code, Status};
17use std::error::Error as _;
18
19pub use crate::from_value::{ConvertError, SharedError};
20pub use crate::omni::TlsError;
21pub use crate::row::RowError;
22pub use wkt::{DurationError, TimestampError};
23
24/// An unexpected error that occurs when the client receives data from Spanner
25/// that it cannot properly parse or handle. This typically indicates a bug in
26/// the client library or the Spanner service itself, though other causes are possible.
27///
28/// # Troubleshooting
29///
30/// This indicates a bug in the client, the service, or a message corrupted
31/// while in transit. Please [open an issue] with as much detail as possible.
32///
33/// [open an issue]: https://github.com/googleapis/google-cloud-rust/issues/new/choose
34#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
35#[non_exhaustive]
36pub enum SpannerInternalError {
37    /// Indicates that Spanner returned data in an unexpected or unparsable format.
38    ///
39    /// This represents an unexpected state and is an indication of an internal bug.
40    #[error("unexpected data received from Spanner: {0}")]
41    UnexpectedData(String),
42}
43
44impl SpannerInternalError {
45    pub(crate) fn new(message: impl Into<String>) -> Self {
46        Self::UnexpectedData(message.into())
47    }
48}
49
50pub(crate) fn internal_error(message: impl Into<String>) -> crate::Error {
51    crate::Error::deser(SpannerInternalError::new(message))
52}
53
54/// An error that occurs when an `execute_batch_update` partially succeeds.
55///
56/// It contains the update counts for each statement evaluated prior to the failure,
57/// as well as the underlying error that caused the batch to fail.
58///
59/// Statements are executed serially in the order provided in the batch.
60/// The `update_counts` correspond to the executed statements in the original
61/// request based on their relative order. The statement that failed is the
62/// one that follows directly after the last statement with an update count.
63/// Execution stops at the first failed statement, and the remaining statements
64/// are not executed.
65#[derive(thiserror::Error, Debug)]
66#[error("{status}")]
67#[non_exhaustive]
68pub struct BatchUpdateError {
69    /// The number of rows modified by each successful statement before the failure.
70    pub update_counts: Vec<i64>,
71    /// The error that caused the batch to fail.
72    #[source]
73    pub status: crate::Error,
74}
75
76impl BatchUpdateError {
77    /// Extracts a `BatchUpdateError` from a `google_cloud_spanner::Error`, if present.
78    pub fn extract(err: &crate::Error) -> Option<&Self> {
79        err.source()
80            .and_then(|source| source.downcast_ref::<BatchUpdateError>())
81    }
82
83    pub(crate) fn build_error(update_counts: Vec<i64>, grpc_status: Status) -> crate::Error {
84        let status = crate::Error::service(grpc_status.clone());
85        let err = Self {
86            update_counts,
87            status,
88        };
89        crate::Error::service_full(grpc_status, None, None, Some(Box::new(err)))
90    }
91}
92
93pub(crate) fn aborted_due_to_failed_initial_statement() -> Error {
94    Error::service(
95        Status::default()
96            .set_code(Code::Aborted)
97            .set_message("Aborted due to failed initial statement"),
98    )
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104    use google_cloud_gax::error::rpc::Code;
105    use static_assertions::assert_impl_all;
106    use std::fmt::Debug;
107
108    #[test]
109    fn auto_traits() {
110        assert_impl_all!(BatchUpdateError: Send, Sync, Debug);
111        assert_impl_all!(SpannerInternalError: Send, Sync, Debug, Clone, PartialEq, Eq);
112    }
113
114    #[test]
115    fn extract_success() {
116        let update_counts = vec![1, 2, 3];
117        let grpc_status = Status::default()
118            .set_code(Code::Aborted)
119            .set_message("Batch failed");
120
121        let err = BatchUpdateError::build_error(update_counts.clone(), grpc_status);
122
123        let extracted = BatchUpdateError::extract(&err).expect("should extract BatchUpdateError");
124        assert_eq!(extracted.update_counts, update_counts);
125        assert_eq!(
126            extracted
127                .status
128                .status()
129                .expect("status should be populated")
130                .code,
131            Code::Aborted
132        );
133    }
134
135    #[test]
136    fn extract_failure() {
137        let grpc_status = Status::default()
138            .set_code(Code::Unknown)
139            .set_message("Regular error");
140        let err = crate::Error::service(grpc_status);
141
142        let extracted = BatchUpdateError::extract(&err);
143        assert!(
144            extracted.is_none(),
145            "should not extract BatchUpdateError from standard service error"
146        );
147    }
148}