Skip to main content

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                IssueType::Throttled(_) => axum::http::StatusCode::TOO_MANY_REQUESTS,
15                _ => axum::http::StatusCode::INTERNAL_SERVER_ERROR,
16            },
17            None => axum::http::StatusCode::INTERNAL_SERVER_ERROR,
18        }
19    }
20}
21
22impl IntoResponse for OperationOutcomeError {
23    fn into_response(self) -> axum::response::Response {
24        let status_code = self.status();
25        let error = Arc::new(self);
26        let outcome = &error.outcome;
27        let mut headers = axum::http::HeaderMap::new();
28        headers.insert(
29            axum::http::header::CONTENT_TYPE,
30            "application/fhir+json".parse().unwrap(),
31        );
32        let response = haste_fhir_serialization_json::to_string(outcome)
33            .expect("Failed to serialize OperationOutcome");
34
35        // Attach the original error to the response extensions for logging middleware to access and content-type handling.
36        let mut response = (status_code, headers, response).into_response();
37        response.extensions_mut().insert(error);
38
39        response
40    }
41}