use axum::Json; use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use serde::Serialize; use thiserror::Error; use cache::redis::RedisError; use storage::StorageError; pub type UserResult = Result; #[derive(Debug, Error)] pub enum UserError { #[error("bad request: {0}")] BadRequest(String), #[error("unauthorized: {0}")] Unauthorized(String), #[error("forbidden: {0}")] Forbidden(String), #[error("not found: {0}")] NotFound(String), #[error("conflict: {0}")] Conflict(String), #[error("rate limited: {0}")] RateLimited(String), #[error("internal error: {0}")] Internal(String), #[error("database error: {0}")] Sqlx(#[from] db::conn::SqlxError), #[error("redis error: {0}")] Redis(#[from] RedisError), #[error("storage error: {0}")] Storage(#[from] StorageError), #[error("uuid: {0}")] Uuid(#[from] uuid::Error), } impl From for UserError { fn from(re: axum::extract::rejection::JsonRejection) -> Self { UserError::BadRequest(re.body_text()) } } impl From for UserError { fn from(re: axum::extract::rejection::PathRejection) -> Self { UserError::BadRequest(re.body_text()) } } impl From for UserError { fn from(re: axum::extract::rejection::QueryRejection) -> Self { UserError::BadRequest(re.body_text()) } } impl UserError { fn status(&self) -> StatusCode { match self { UserError::BadRequest(_) => StatusCode::BAD_REQUEST, UserError::Forbidden(_) => StatusCode::FORBIDDEN, UserError::Conflict(_) => StatusCode::CONFLICT, UserError::Unauthorized(_) => StatusCode::UNAUTHORIZED, UserError::NotFound(_) => StatusCode::NOT_FOUND, UserError::RateLimited(_) => StatusCode::TOO_MANY_REQUESTS, UserError::Internal(_) | UserError::Sqlx(_) | UserError::Redis(_) | UserError::Storage(_) | UserError::Uuid(_) => StatusCode::INTERNAL_SERVER_ERROR, } } fn is_user_facing(&self) -> bool { matches!( self, UserError::BadRequest(_) | UserError::Unauthorized(_) | UserError::Forbidden(_) | UserError::NotFound(_) | UserError::Conflict(_) | UserError::RateLimited(_) ) } } #[derive(Serialize)] struct ErrorBody<'a> { error: &'a str, } impl IntoResponse for UserError { fn into_response(self) -> Response { let status = self.status(); let msg = if self.is_user_facing() { self.to_string() } else { tracing::error!(error = %self, "user internal error"); "internal error".to_string() }; let body = ErrorBody { error: &msg }; (status, Json(body)).into_response() } }