use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use export::data::{AppResponseData, NoData}; use thiserror::Error; pub type PostResult = Result; #[derive(Debug, Error)] pub enum PostError { #[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 PostError { fn from(re: axum::extract::rejection::JsonRejection) -> Self { PostError::BadRequest(re.body_text()) } } impl From for PostError { fn from(re: axum::extract::rejection::PathRejection) -> Self { PostError::BadRequest(re.body_text()) } } impl From for PostError { fn from(re: axum::extract::rejection::QueryRejection) -> Self { PostError::BadRequest(re.body_text()) } } impl PostError { fn status(&self) -> StatusCode { match self { PostError::BadRequest(_) => StatusCode::BAD_REQUEST, PostError::Unauthorized(_) => StatusCode::UNAUTHORIZED, PostError::Forbidden(_) => StatusCode::FORBIDDEN, PostError::NotFound(_) => StatusCode::NOT_FOUND, PostError::Conflict(_) => StatusCode::CONFLICT, PostError::Unprocessable(_) => StatusCode::UNPROCESSABLE_ENTITY, PostError::RateLimited(_) => StatusCode::TOO_MANY_REQUESTS, PostError::Internal(_) | PostError::Sqlx(_) | PostError::Uuid(_) => { StatusCode::INTERNAL_SERVER_ERROR } } } fn is_user_facing(&self) -> bool { matches!( self, PostError::BadRequest(_) | PostError::Unauthorized(_) | PostError::Forbidden(_) | PostError::NotFound(_) | PostError::Conflict(_) | PostError::Unprocessable(_) | PostError::RateLimited(_) ) } pub fn error_kind(&self) -> &'static str { match self { PostError::BadRequest(_) => "bad_request", PostError::Unauthorized(_) => "unauthorized", PostError::Forbidden(_) => "forbidden", PostError::NotFound(_) => "not_found", PostError::Conflict(_) => "conflict", PostError::Unprocessable(_) => "unprocessable", PostError::RateLimited(_) => "rate_limited", PostError::Internal(_) => "internal_other", PostError::Sqlx(_) => "internal_db", PostError::Uuid(_) => "internal_uuid", } } } impl IntoResponse for PostError { fn into_response(self) -> Response { let status = self.status(); let msg = if self.is_user_facing() { self.to_string() } else { tracing::error!(error = %self, "post internal error"); "internal error".to_string() }; AppResponseData::::err_plain(status.as_u16() as i32, msg).into_response() } }