cx_sdk/
error.rs

1// Copyright 2024 Coralogix Ltd.
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 http::uri::InvalidUri;
16use tonic::transport::Error as TonicError;
17use tonic_types::{
18    ErrorDetails,
19    StatusExt,
20};
21
22/// The result type for the SDK.
23pub type Result<T> = std::result::Result<T, SdkError>;
24
25/// An error returned by the underlying API.
26#[derive(Debug, thiserror::Error)]
27pub struct SdkApiError {
28    /// The status code of the error.
29    pub status: tonic::Status,
30    /// The endpoint that the error occurred on.
31    pub endpoint: String,
32    /// The feature group the endpoint belongs to.
33    pub feature_group: String,
34}
35
36impl SdkApiError {
37    /// The details of a tonic error
38    pub fn details(&self) -> ErrorDetails {
39        self.status.get_error_details()
40    }
41}
42
43impl std::fmt::Display for SdkApiError {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        write!(f, "API error on {}: {}", self.endpoint, self.status)
46    }
47}
48
49/// The error type for the SDK.
50#[derive(Debug, thiserror::Error)]
51pub enum SdkError {
52    /// This error is returned when the team that an operation refers to is not found.
53    #[error("Invalid endpoint URI: {0}")]
54    TeamNotFound(#[from] InvalidUri),
55
56    /// This error is returned when an endpoint is not found.
57    #[error("Endpoint not found: {0}")]
58    EndpointNotFound(#[from] TonicError),
59
60    /// This error is returned when an underying API throws an error.
61    #[error("API error: {0}")]
62    ApiError(#[from] SdkApiError),
63
64    /// This error is returned when an environment variable is not found or is invalid.
65    #[error("Invalid environment variable for CORALOGIX_REGION: {0}")]
66    EnvConfigurationError(#[from] std::env::VarError),
67}