use axum::Json; use axum::extract::rejection::{JsonRejection, PathRejection, QueryRejection}; use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use horoscope_client::HoroscopeError; use serde_json::{Value, json}; /// API error, rendered as `{"error": {"code", "message"}}`. #[derive(Debug, thiserror::Error)] pub enum ApiError { #[error("{0}")] BadRequest(String), #[error("authentication required")] Unauthorized, #[error("{0}")] InvalidCredentials(String), #[error("{0}")] Forbidden(String), #[error("{0} not found")] NotFound(&'static str), #[error("{message}")] Conflict { code: &'static str, message: String }, #[error("{0}")] Gone(String), #[error("the link is invalid or has expired")] InvalidToken, #[error("no {unit} analysis left (balance {balance})")] InsufficientCredits { unit: &'static str, balance: i64 }, #[error("too many attempts; try again later")] TooManyRequests, /// A usage limit; the message is shown to the user as is. #[error("{message}")] Limited { code: &'static str, message: String }, /// Birth data rejected by the horoscope service; its error object is passed through. #[error("invalid birth data")] BirthData { status: StatusCode, body: Value }, #[error("horoscope service unavailable")] HoroscopeUnavailable(String), #[error("internal error")] Internal(String), } impl ApiError { pub fn conflict(code: &'static str, message: impl Into) -> Self { ApiError::Conflict { code, message: message.into() } } fn status_and_code(&self) -> (StatusCode, &'static str) { match self { ApiError::BadRequest(_) => (StatusCode::BAD_REQUEST, "bad_request"), ApiError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized"), ApiError::InvalidCredentials(_) => (StatusCode::UNAUTHORIZED, "invalid_credentials"), ApiError::Forbidden(_) => (StatusCode::FORBIDDEN, "forbidden"), ApiError::NotFound(_) => (StatusCode::NOT_FOUND, "not_found"), ApiError::Conflict { code, .. } => (StatusCode::CONFLICT, code), ApiError::Gone(_) => (StatusCode::GONE, "gone"), ApiError::InvalidToken => (StatusCode::BAD_REQUEST, "invalid_token"), ApiError::InsufficientCredits { .. } => (StatusCode::PAYMENT_REQUIRED, "insufficient_credits"), ApiError::TooManyRequests => (StatusCode::TOO_MANY_REQUESTS, "too_many_requests"), ApiError::Limited { code, .. } => (StatusCode::TOO_MANY_REQUESTS, code), ApiError::BirthData { status, .. } => (*status, "invalid_birth_data"), ApiError::HoroscopeUnavailable(_) => (StatusCode::BAD_GATEWAY, "horoscope_unavailable"), ApiError::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "internal_error"), } } } impl IntoResponse for ApiError { fn into_response(self) -> Response { let (status, code) = self.status_and_code(); match &self { ApiError::Internal(detail) | ApiError::HoroscopeUnavailable(detail) => { tracing::error!(error = %detail, code, "request failed"); } _ => {} } let body = match self { // Keep the horoscope service's code, message and place suggestions. ApiError::BirthData { body, .. } => { body.get("error").cloned().map(|e| json!({ "error": e })).unwrap_or(body) } other => json!({ "error": { "code": code, "message": other.to_string() } }), }; (status, Json(body)).into_response() } } impl From for ApiError { fn from(e: sqlx::Error) -> Self { ApiError::Internal(format!("database: {e}")) } } impl From for ApiError { fn from(e: HoroscopeError) -> Self { match e { HoroscopeError::Rejected { status, body } => { ApiError::BirthData { status: StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_REQUEST), body } } HoroscopeError::Unavailable(detail) => ApiError::HoroscopeUnavailable(detail), } } } impl From for ApiError { fn from(rejection: JsonRejection) -> Self { ApiError::BadRequest(rejection.body_text()) } } impl From for ApiError { fn from(rejection: QueryRejection) -> Self { ApiError::BadRequest(rejection.body_text()) } } impl From for ApiError { fn from(rejection: PathRejection) -> Self { ApiError::BadRequest(rejection.body_text()) } } pub type ApiResult = Result;