//! Shared error response shape for all endpoints, modeled on RFC 7807 //! (Problem Details for HTTP APIs) plus a few extra fields: a machine //! readable `code`, the OpenAPI `operation_id` that failed, a `spec_url` //! pointing back at /openapi.json, the request's `request_id` (see the //! SetRequestIdLayer/PropagateRequestIdLayer in lib.rs), and `next`, a //! hint at a related endpoint the caller might try instead. //! //! `type`/`spec_url` are relative paths, not absolute URLs, since this //! service has no fixed public domain; RFC 7807 explicitly allows `type` //! to be a relative URI reference. use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use axum::Json; use serde::Serialize; #[derive(Serialize, utoipa::ToSchema)] pub struct ApiError { pub r#type: String, pub title: String, pub status: u16, pub code: String, pub detail: String, pub operation_id: String, pub spec_url: String, pub request_id: Option, pub next: Option, } impl ApiError { pub fn new(status: StatusCode, code: &str, title: &str, detail: String, operation_id: &str) -> Self { ApiError { r#type: format!("/errors/{code}"), title: title.to_string(), status: status.as_u16(), code: code.to_string(), detail, operation_id: operation_id.to_string(), spec_url: "/openapi.json".to_string(), request_id: None, next: None, } } pub fn with_request_id(mut self, request_id: Option) -> Self { self.request_id = request_id; self } pub fn with_next(mut self, next: &str) -> Self { self.next = Some(next.to_string()); self } } impl IntoResponse for ApiError { fn into_response(self) -> Response { let status = StatusCode::from_u16(self.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR); (status, Json(self)).into_response() } }