hl7-net 0.1.0

Lightweight HL7 V2 parser/writer, ported from the Efferent HL7-V2 .NET library
Documentation
use std::fmt;

/// Error type for HL7 message processing (parsing, validation, serialization).
///
/// Mirrors the .NET `HL7Exception`: it carries a human readable `message` plus an
/// optional `code` taken from the set of well known categories below.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Hl7Error {
    /// Human readable description of what went wrong.
    pub message: String,
    /// Optional category for the error (one of the associated constants).
    pub code: Option<String>,
}

impl Hl7Error {
    /// Validation error due to a required field missing in the message.
    pub const REQUIRED_FIELD_MISSING: &'static str =
        "Validation Error - Required field missing in message";
    /// Validation error where the message type is not supported by this implementation.
    pub const UNSUPPORTED_MESSAGE_TYPE: &'static str =
        "Validation Error - Message Type not supported by this implementation";
    /// Validation error due to a malformed or invalid message.
    pub const BAD_MESSAGE: &'static str = "Validation Error - Bad Message";
    /// Error that occurred during parsing of the HL7 message.
    pub const PARSING_ERROR: &'static str = "Parsing Error";
    /// Error that occurred during serialization of the HL7 message.
    pub const SERIALIZATION_ERROR: &'static str = "Serialization Error";

    /// Creates an error with just a message and no category code.
    pub fn new(message: impl Into<String>) -> Self {
        Self { message: message.into(), code: None }
    }

    /// Creates an error with a message and a category code.
    pub fn with_code(message: impl Into<String>, code: impl Into<String>) -> Self {
        Self { message: message.into(), code: Some(code.into()) }
    }
}

impl fmt::Display for Hl7Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.code {
            Some(code) => write!(f, "{code} : {}", self.message),
            None => write!(f, "{}", self.message),
        }
    }
}

impl std::error::Error for Hl7Error {}