Skip to main content

hl7_net/
error.rs

1use std::fmt;
2
3/// Error type for HL7 message processing (parsing, validation, serialization).
4///
5/// Mirrors the .NET `HL7Exception`: it carries a human readable `message` plus an
6/// optional `code` taken from the set of well known categories below.
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub struct Hl7Error {
9    /// Human readable description of what went wrong.
10    pub message: String,
11    /// Optional category for the error (one of the associated constants).
12    pub code: Option<String>,
13}
14
15impl Hl7Error {
16    /// Validation error due to a required field missing in the message.
17    pub const REQUIRED_FIELD_MISSING: &'static str =
18        "Validation Error - Required field missing in message";
19    /// Validation error where the message type is not supported by this implementation.
20    pub const UNSUPPORTED_MESSAGE_TYPE: &'static str =
21        "Validation Error - Message Type not supported by this implementation";
22    /// Validation error due to a malformed or invalid message.
23    pub const BAD_MESSAGE: &'static str = "Validation Error - Bad Message";
24    /// Error that occurred during parsing of the HL7 message.
25    pub const PARSING_ERROR: &'static str = "Parsing Error";
26    /// Error that occurred during serialization of the HL7 message.
27    pub const SERIALIZATION_ERROR: &'static str = "Serialization Error";
28
29    /// Creates an error with just a message and no category code.
30    pub fn new(message: impl Into<String>) -> Self {
31        Self { message: message.into(), code: None }
32    }
33
34    /// Creates an error with a message and a category code.
35    pub fn with_code(message: impl Into<String>, code: impl Into<String>) -> Self {
36        Self { message: message.into(), code: Some(code.into()) }
37    }
38}
39
40impl fmt::Display for Hl7Error {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        match &self.code {
43            Some(code) => write!(f, "{code} : {}", self.message),
44            None => write!(f, "{}", self.message),
45        }
46    }
47}
48
49impl std::error::Error for Hl7Error {}