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    #[must_use]
8    pub fn status(&self) -> axum::http::StatusCode {
9        match self.outcome.issue.first() {
10            Some(issue) => {
11                if issue.code == IssueType::invalid() {
12                    axum::http::StatusCode::BAD_REQUEST
13                } else if issue.code == IssueType::not_found() {
14                    axum::http::StatusCode::NOT_FOUND
15                } else if issue.code == IssueType::forbidden() {
16                    axum::http::StatusCode::FORBIDDEN
17                } else if issue.code == IssueType::conflict() {
18                    axum::http::StatusCode::CONFLICT
19                } else if issue.code == IssueType::throttled() {
20                    axum::http::StatusCode::TOO_MANY_REQUESTS
21                } else {
22                    axum::http::StatusCode::INTERNAL_SERVER_ERROR
23                }
24            }
25            None => axum::http::StatusCode::INTERNAL_SERVER_ERROR,
26        }
27    }
28}
29
30impl IntoResponse for OperationOutcomeError {
31    fn into_response(self) -> axum::response::Response {
32        let status_code = self.status();
33        let error = Arc::new(self);
34        let outcome = &error.outcome;
35        let mut headers = axum::http::HeaderMap::new();
36        headers.insert(
37            axum::http::header::CONTENT_TYPE,
38            "application/fhir+json".parse().unwrap(),
39        );
40        let response =
41            serde_json::to_string(outcome).expect("Failed to serialize OperationOutcome");
42
43        // Attach the original error to the response extensions for logging middleware to access and content-type handling.
44        let mut response = (status_code, headers, response).into_response();
45        response.extensions_mut().insert(error);
46
47        response
48    }
49}