|
| 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 | + |
| 15 | +use axum::http::StatusCode; |
| 16 | +use axum::response::{IntoResponse, Response}; |
| 17 | +use google_cloud_auth::build_errors::Error as BuildError; |
| 18 | +use google_cloud_gax::client_builder::Error as ClientBuilderError; |
| 19 | +use google_cloud_gax::error::Error; |
| 20 | + |
| 21 | +#[derive(Debug, thiserror::Error)] |
| 22 | +pub enum AppError { |
| 23 | + #[error("the backend reported an error: {0}")] |
| 24 | + Backend(#[source] Error), |
| 25 | + #[error("the backend response had an unexpected format: {0}")] |
| 26 | + BadResponseFormat(String), |
| 27 | + #[error("there was a problem contacting the backend: {0}")] |
| 28 | + Request(#[source] Error), |
| 29 | + #[error("cannot initialize the service credentials: {0}")] |
| 30 | + Credentials(#[source] BuildError), |
| 31 | + #[error("cannot initialize a client: {0}")] |
| 32 | + Client(#[source] ClientBuilderError), |
| 33 | +} |
| 34 | + |
| 35 | +impl From<Error> for AppError { |
| 36 | + fn from(value: Error) -> Self { |
| 37 | + if value.status().is_some() { |
| 38 | + Self::Backend(value) |
| 39 | + } else { |
| 40 | + Self::Request(value) |
| 41 | + } |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +impl From<BuildError> for AppError { |
| 46 | + fn from(value: BuildError) -> Self { |
| 47 | + Self::Credentials(value) |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +impl From<ClientBuilderError> for AppError { |
| 52 | + fn from(value: ClientBuilderError) -> Self { |
| 53 | + Self::Client(value) |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +impl IntoResponse for AppError { |
| 58 | + fn into_response(self) -> Response { |
| 59 | + tracing::error!("internal service error: {self:?}"); |
| 60 | + let (status, message) = match self { |
| 61 | + Self::Backend(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e:?}")), |
| 62 | + Self::BadResponseFormat(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e:?}")), |
| 63 | + Self::Request(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e:#?}")), |
| 64 | + Self::Credentials(e) => (StatusCode::UNAUTHORIZED, format!("{e:#?}")), |
| 65 | + Self::Client(e) => (StatusCode::SERVICE_UNAVAILABLE, format!("{e:#?}")), |
| 66 | + }; |
| 67 | + (status, message).into_response() |
| 68 | + } |
| 69 | +} |
0 commit comments