Files
sorsfonalak/services/backend/src/error.rs
T
fecoandClaude Opus 5.5 7272d0f1f3 Invitation-only sign-up, invitation e-mails and waitlist
- SIGNUP_MODE=invite (default): a new account needs an open invitation for
  its address, or the invitation link (then any Google account will do)
- admin page "Meghívók": invite many addresses at once, personal message,
  resend (max 3, 24 h apart), revoke, copy link, mail preview and test copy,
  waitlist
- invitation e-mail in HTML and plain text; Message-ID on the sender's
  domain, List-Unsubscribe with one-click POST, opt-out list (hashes only)
- e-mail texts moved to a shared crate (crates/email-templates)
- login page shows the invitation; waitlist for uninvited visitors;
  unsubscribe page; privacy policy updated
- docs/levelkuldes.md: Brevo, DNS (SPF, DKIM, DMARC) and the SMTP setup

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

128 lines
4.8 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),
/// Refused, with a code the frontend acts on (e.g. `not_invited`).
#[error("{message}")]
Refused { code: &'static str, message: 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::Refused { code, .. } => (StatusCode::FORBIDDEN, code),
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>;