3.3 KiB · text History 6e34613
//! The one error shape every `/api/v1` response uses (party-slut's
//! `src/api/error.rs`): `{"error": {"code", "message", "details"}}`. `code`
//! is for the program, `message` for the person.
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::Json;
use serde_json::{json, Value};

use crate::actions::ActionError;

#[derive(Debug)]
pub struct ApiError {
    pub status: StatusCode,
    pub code: &'static str,
    pub message: String,
    pub details: Option<Value>,
}

impl ApiError {
    pub fn new(status: StatusCode, code: &'static str, message: impl Into<String>) -> Self {
        Self { status, code, message: message.into(), details: None }
    }

    pub fn with_details(mut self, details: Value) -> Self {
        self.details = Some(details);
        self
    }

    /// No token, an unknown, expired or revoked one, or a deactivated
    /// account. Deliberately one answer: the app does the same for all four
    /// (pair again), and telling them apart only helps someone guessing.
    pub fn unauthorized() -> Self {
        Self::new(StatusCode::UNAUTHORIZED, "unauthorized", "Pair this device again to continue.")
    }

    pub fn not_found(message: impl Into<String>) -> Self {
        Self::new(StatusCode::NOT_FOUND, "not_found", message)
    }

    pub fn invalid(message: impl Into<String>) -> Self {
        Self::new(StatusCode::UNPROCESSABLE_ENTITY, "invalid", message)
    }

    /// Something broke on our side. The cause is logged, never sent.
    pub fn internal(cause: impl std::fmt::Display) -> Self {
        tracing::error!(error = %cause, "api request failed");
        Self::new(StatusCode::INTERNAL_SERVER_ERROR, "internal", "Something went wrong on our side.")
    }
}

impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        let body = json!({
            "error": { "code": self.code, "message": self.message, "details": self.details }
        });
        (self.status, Json(body)).into_response()
    }
}

impl From<ActionError> for ApiError {
    fn from(e: ActionError) -> Self {
        match e {
            ActionError::NotFound => ApiError::not_found("We couldn't find that."),
            ActionError::Unverified => ApiError::new(
                StatusCode::FORBIDDEN,
                "unverified",
                "Verify your email address to post, react or bookmark.",
            ),
            ActionError::Forbidden { code, message } => ApiError::new(StatusCode::FORBIDDEN, code, message),
            ActionError::Conflict { code, message } => ApiError::new(StatusCode::CONFLICT, code, message),
            ActionError::Invalid(message) => ApiError::invalid(message),
            ActionError::TooLong(message) => ApiError::new(StatusCode::PAYLOAD_TOO_LARGE, "too_long", message),
            ActionError::Internal(e) => ApiError::internal(e),
        }
    }
}

/// The listing helpers shared with the web answer bare status codes.
impl From<StatusCode> for ApiError {
    fn from(s: StatusCode) -> Self {
        ActionError::from(s).into()
    }
}

impl From<sea_orm::DbErr> for ApiError {
    fn from(e: sea_orm::DbErr) -> Self {
        ApiError::internal(e)
    }
}

impl From<anyhow::Error> for ApiError {
    fn from(e: anyhow::Error) -> Self {
        ApiError::internal(e)
    }
}

pub type ApiResult<T> = Result<T, ApiError>;