haste_fhir_operation_error/
axum.rs

1use crate::OperationOutcomeError;
2use axum::response::IntoResponse;
3use haste_fhir_model::r4::generated::terminology::IssueType;
4use std::sync::Arc;
5
6impl OperationOutcomeError {
7    pub fn status(&self) -> axum::http::StatusCode {
8        match self.outcome.issue.first() {
9            Some(issue) => match issue.code.as_ref() {
10                IssueType::Invalid(_) => axum::http::StatusCode::BAD_REQUEST,
11                IssueType::NotFound(_) => axum::http::StatusCode::NOT_FOUND,
12                IssueType::Forbidden(_) => axum::http::StatusCode::FORBIDDEN,
13                IssueType::Conflict(_) => axum::http::StatusCode::CONFLICT,
14                _ => axum::http::StatusCode::INTERNAL_SERVER_ERROR,
15            },
16            None => axum::http::StatusCode::INTERNAL_SERVER_ERROR,
17        }
18    }
19}
20
21impl IntoResponse for OperationOutcomeError {
22    fn into_response(self) -> axum::response::Response {
23        let status_code = self.status();
24        let error = Arc::new(self);
25        let outcome = &error.outcome;
26        let mut headers = axum::http::HeaderMap::new();
27        headers.insert(
28            axum::http::header::CONTENT_TYPE,
29            "application/fhir+json".parse().unwrap(),
30        );
31        let response = haste_fhir_serialization_json::to_string(outcome)
32            .expect("Failed to serialize OperationOutcome");
33
34        // Attach the original error to the response extensions for logging middleware to access and content-type handling.
35        let mut response = (status_code, headers, response).into_response();
36        response.extensions_mut().insert(error);
37
38        response
39    }
40}