refactor: single refusal shape with openapi contract test

This commit is contained in:
2026-10-25 21:55:38 +01:00
parent 816d39ffd6
commit c8d9138349
25 changed files with 764 additions and 273 deletions

View File

@@ -1,9 +1,30 @@
use api_types::ErrorResponse;
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
use domain::errors::DomainError;
pub const NOT_FOUND: &str = "NOT_FOUND";
pub const INVALID_INPUT: &str = "INVALID_INPUT";
pub const CONFLICT: &str = "CONFLICT";
pub const UNAUTHORIZED: &str = "UNAUTHORIZED";
pub const FORBIDDEN: &str = "FORBIDDEN";
pub const RATE_LIMITED: &str = "RATE_LIMITED";
pub const INTERNAL: &str = "INTERNAL";
/// The only constructor of JSON error bodies in this crate.
pub fn refuse(status: StatusCode, code: &'static str, message: impl Into<String>) -> Response {
(
status,
axum::Json(ErrorResponse {
error: message.into(),
code: code.to_string(),
}),
)
.into_response()
}
pub fn domain_error_status(e: &DomainError) -> StatusCode {
match e {
DomainError::InvalidRating { .. } | DomainError::ValidationError(_) => {
@@ -38,19 +59,16 @@ impl IntoResponse for ApiError {
fn into_response(self) -> Response {
let status = domain_error_status(&self.0);
match &self.0 {
DomainError::InvalidRating { .. } | DomainError::ValidationError(_) => {
refuse(status, INVALID_INPUT, self.0.to_string())
}
DomainError::NotFound(_) => refuse(status, NOT_FOUND, self.0.to_string()),
DomainError::Unauthorized(_) => refuse(status, UNAUTHORIZED, self.0.to_string()),
DomainError::Forbidden(_) => refuse(status, FORBIDDEN, self.0.to_string()),
DomainError::InfrastructureError(_) => {
tracing::error!("Internal error: {:?}", self.0);
(
status,
axum::Json(serde_json::json!({"error": "internal server error"})),
)
.into_response()
refuse(status, INTERNAL, "internal server error")
}
_ => (
status,
axum::Json(serde_json::json!({"error": self.0.to_string()})),
)
.into_response(),
}
}
}