Files
sorsfonalak/services/backend/src/error.rs
T
fecoandClaude Opus 5.5 e5cfbd6cdd
CI / test (push) Successful in 41s
CI / build (push) Successful in 4m11s
CI / deploy (push) Skipped
Detailed analysis button, loading wheel, birth data change limits
Backend:
- own birth data: three corrections within an hour of the first save,
  then one change per 24 hours (birth_data_changes); 429
  birth_data_change_limit with the user-facing message; /v1/me
  birth_change shows the notice; admins are not limited
- admins get detailed analyses free (no unit spent)
- POST /v1/payments/mock (MOCK_PAYMENTS): stand-in payment that adds a
  unit, until Stripe is connected; on in the compose files for now

Frontend:
- detailed analysis offer: admin starts it free, users with units
  confirm, others go through the (stand-in) payment step
- turning wheel with elapsed time while the summary or the analysis is
  being written
- no "adatok javítása" on the chart page (only in the profile), limit
  notice there; wheel hover highlighting removed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-17 06:45:33 +00:00

124 lines
4.6 KiB
Rust

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<String>) -> 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<sqlx::Error> for ApiError {
fn from(e: sqlx::Error) -> Self {
ApiError::Internal(format!("database: {e}"))
}
}
impl From<HoroscopeError> 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<JsonRejection> for ApiError {
fn from(rejection: JsonRejection) -> Self {
ApiError::BadRequest(rejection.body_text())
}
}
impl From<QueryRejection> for ApiError {
fn from(rejection: QueryRejection) -> Self {
ApiError::BadRequest(rejection.body_text())
}
}
impl From<PathRejection> for ApiError {
fn from(rejection: PathRejection) -> Self {
ApiError::BadRequest(rejection.body_text())
}
}
pub type ApiResult<T> = Result<T, ApiError>;