use fhir_types::codec::DecodeError;
use fhir_types::operation::ParametersError;
use fhir_types::r4::operation_outcome::OperationOutcome;
use openehr_mapping_core::template::PathError;
use crate::engine::seam::ReferenceError;
use crate::engine::traverse::error::EngineError;
use crate::operations::issues;
use crate::resolve::select::SelectError;
#[derive(Debug, thiserror::Error)]
pub enum OperationError {
#[error("the ${operation} request does not fit its declared parameters")]
Parameters {
operation: &'static str,
#[source]
source: ParametersError,
},
#[error("the ${operation} body is not a {expected}")]
Body {
operation: &'static str,
expected: &'static str,
#[source]
source: Box<DecodeError>,
},
#[error("the composition parameter does not hold a JSON object")]
Payload {
#[source]
source: serde_json::Error,
},
#[error("the {what} is not a JSON object")]
NotAnObject {
what: &'static str,
},
#[error("a resource of the bundle does not render as JSON")]
Encode {
#[source]
source: fhir_types::codec::EncodeError,
},
#[error("a flat composition carries no template, so `templateId` is required")]
FlatTemplate,
#[error(
"the composition names no `archetype_details.template_id`, so `templateId` is required"
)]
CanonicalTemplate,
#[error("the composition names the template `{payload}` and the request pins `{pinned}`")]
TemplateDisagreement {
payload: String,
pinned: String,
},
#[error("no operational template `{template}` is loaded")]
UnknownTemplate {
template: String,
},
#[error("no single mapping answers this request")]
Select {
#[source]
source: SelectError,
},
#[error("the bundle carries no {resource} for the mapping `{context}`")]
NoSubjectResource {
resource: String,
context: String,
},
#[error("the bundle carries {count} {resource} resources, and one run maps one")]
SeveralSubjectResources {
resource: String,
count: usize,
},
#[error("the bundle references {} subjects: {}", subjects.len(), subjects.join(", "))]
SeveralSubjects {
subjects: Vec<String>,
},
#[error("the mapping did not run to completion")]
Mapping {
#[source]
source: Box<EngineError>,
},
#[error("the composition could not be converted between its serializations")]
Serialization {
#[source]
source: Box<PathError>,
},
#[error("the mapping produced a document the {version} model does not admit")]
Mapped {
version: &'static str,
#[source]
source: Box<DecodeError>,
},
#[error(
"the mapped {resource} carries no `id` and the composition carries no `uid`, so the \
Provenance has nothing to target"
)]
Unidentified {
resource: String,
},
#[error("two resources of the answer take the identity {reference}")]
DuplicateId {
reference: String,
},
#[error("the identity seam assigned the mapped {resource} no id")]
Identity {
resource: String,
#[source]
source: ReferenceError,
},
#[error("the identity seam assigned the mapped {resource} the id `{id}`, which is no FHIR id")]
InvalidId {
resource: String,
id: String,
},
}
impl OperationError {
#[must_use]
pub fn issue_type(&self) -> &'static str {
match *self {
Self::Parameters { ref source, .. } => parameters_issue_type(source),
Self::Body { .. }
| Self::Payload { .. }
| Self::NotAnObject { .. }
| Self::Encode { .. }
| Self::Mapped { .. } => "structure",
Self::FlatTemplate | Self::CanonicalTemplate => "required",
Self::TemplateDisagreement { .. } => "invalid",
Self::UnknownTemplate { .. } | Self::NoSubjectResource { .. } => "not-found",
Self::Select { ref source } => match *source {
SelectError::Ambiguous { .. } => "multiple-matches",
SelectError::NoMatch { .. } | SelectError::ProfileVersion { .. } => "not-found",
},
Self::SeveralSubjectResources { .. } | Self::SeveralSubjects { .. } => "business-rule",
Self::Mapping { .. }
| Self::Serialization { .. }
| Self::Unidentified { .. }
| Self::DuplicateId { .. } => "processing",
Self::Identity { .. } => "exception",
Self::InvalidId { .. } => "value",
}
}
#[must_use]
pub fn outcome(&self) -> OperationOutcome {
OperationOutcome {
issue: vec![issues::issue(
issues::ERROR,
self.issue_type(),
&self.rendered(),
)],
..OperationOutcome::default()
}
}
fn rendered(&self) -> String {
let mut line = self.to_string();
let mut cause: Option<&dyn core::error::Error> = core::error::Error::source(self);
while let Some(source) = cause {
line.push_str(": ");
line.push_str(&source.to_string());
cause = source.source();
}
line
}
}
fn parameters_issue_type(error: &ParametersError) -> &'static str {
match *error {
ParametersError::Unnamed { .. }
| ParametersError::Undeclared { .. }
| ParametersError::Repeated { .. } => "structure",
ParametersError::Missing { .. } | ParametersError::MissingValue { .. } => "required",
ParametersError::WrongType { .. } => "value",
}
}
#[cfg(test)]
mod tests {
use super::OperationError;
use fhir_types::operation::ParametersError;
#[test]
fn a_flat_payload_without_a_template_is_required() {
let error = OperationError::FlatTemplate;
assert_eq!(error.issue_type(), "required");
let outcome = error.outcome();
assert_eq!(outcome.issue.len(), 1);
assert_eq!(
outcome
.issue
.first()
.and_then(|issue| issue.code.value.clone()),
Some(String::from("required"))
);
}
#[test]
fn an_undeclared_parameter_is_a_structural_refusal() {
let error = OperationError::Parameters {
operation: crate::operations::TO_FHIR,
source: ParametersError::Undeclared {
operation: "$tofhir",
name: String::from("subject"),
},
};
assert_eq!(error.issue_type(), "structure");
let outcome = error.outcome();
let text = outcome
.issue
.first()
.and_then(|issue| issue.details.as_ref())
.and_then(|details| details.text.as_ref())
.and_then(|text| text.value.clone())
.unwrap_or_default();
assert!(
text.contains("subject"),
"the outcome names the refused parameter: {text}"
);
}
}