use axum::Json; use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use serde::Serialize; use thiserror::Error; pub type IssueResult = Result; #[derive(Debug, Error)] pub enum IssueError { #[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("unprocessable: {0}")] Unprocessable(String), #[error("rate limited: {0}")] RateLimited(String), #[error("internal: {0}")] Internal(String), #[error("database error: {0}")] Sqlx(#[from] db::conn::SqlxError), #[error("uuid: {0}")] Uuid(#[from] uuid::Error), } impl From for IssueError { fn from(re: axum::extract::rejection::JsonRejection) -> Self { IssueError::BadRequest(re.body_text()) } } impl From for IssueError { fn from(re: axum::extract::rejection::PathRejection) -> Self { IssueError::BadRequest(re.body_text()) } } impl From for IssueError { fn from(re: axum::extract::rejection::QueryRejection) -> Self { IssueError::BadRequest(re.body_text()) } } impl IssueError { fn status(&self) -> StatusCode { match self { IssueError::BadRequest(_) => StatusCode::BAD_REQUEST, IssueError::Unauthorized(_) => StatusCode::UNAUTHORIZED, IssueError::Forbidden(_) => StatusCode::FORBIDDEN, IssueError::NotFound(_) => StatusCode::NOT_FOUND, IssueError::Conflict(_) => StatusCode::CONFLICT, IssueError::Unprocessable(_) => StatusCode::UNPROCESSABLE_ENTITY, IssueError::RateLimited(_) => StatusCode::TOO_MANY_REQUESTS, IssueError::Internal(_) | IssueError::Sqlx(_) | IssueError::Uuid(_) => StatusCode::INTERNAL_SERVER_ERROR, } } fn is_user_facing(&self) -> bool { matches!( self, IssueError::BadRequest(_) | IssueError::Unauthorized(_) | IssueError::Forbidden(_) | IssueError::NotFound(_) | IssueError::Conflict(_) | IssueError::Unprocessable(_) | IssueError::RateLimited(_) ) } } #[derive(Serialize)] struct ErrorBody<'a> { error: &'a str, } impl IntoResponse for IssueError { fn into_response(self) -> Response { let status = self.status(); let msg = if self.is_user_facing() { self.to_string() } else { tracing::error!(error = %self, "issues internal error"); "internal error".to_string() }; (status, Json(ErrorBody { error: &msg })).into_response() } }