1use thiserror::Error;
2
3#[derive(Debug)]
7pub struct IoError(pub(crate) std::io::Error);
8
9impl IoError {
10 pub fn inner(&self) -> &std::io::Error {
12 &self.0
13 }
14}
15
16impl PartialEq for IoError {
17 fn eq(&self, other: &Self) -> bool {
24 self.0.kind() == other.0.kind()
25 }
26}
27
28impl std::fmt::Display for IoError {
29 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30 self.0.fmt(f)
31 }
32}
33
34impl std::error::Error for IoError {
35 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
36 self.0.source()
37 }
38}
39
40impl From<std::io::Error> for IoError {
41 fn from(e: std::io::Error) -> Self {
42 Self(e)
43 }
44}
45
46#[derive(Debug, Error, PartialEq)]
53#[non_exhaustive]
54pub enum EdifactError {
55 #[error("unexpected end of input at byte offset {offset}")]
60 UnexpectedEof {
61 offset: usize,
63 },
64
65 #[error("invalid delimiter byte 0x{byte:02X} at offset {offset}")]
70 InvalidDelimiter {
71 byte: u8,
73 offset: usize,
75 },
76
77 #[error("invalid EDIFACT text at byte offset {offset}")]
82 InvalidText {
83 offset: usize,
85 },
86
87 #[error("invalid release sequence at byte offset {offset}: dangling release character")]
92 InvalidReleaseSequence {
93 offset: usize,
95 },
96
97 #[error("interchange message count mismatch: UNZ declared {expected}, found {actual}")]
102 MessageCountMismatch {
103 expected: u32,
105 actual: u32,
107 },
108
109 #[error(
114 "segment count mismatch in message {message_ref}: UNT declared {expected}, found {actual}"
115 )]
116 SegmentCountMismatch {
117 expected: u32,
119 actual: u32,
121 message_ref: String,
123 },
124
125 #[error("invalid segment tag {0:?}")]
129 InvalidSegmentTag(String),
130
131 #[error("invalid UNA service string advice")]
141 InvalidUna,
142
143 #[error("missing required element {element_index} in segment {tag}")]
148 MissingRequiredElement {
149 tag: String,
151 element_index: usize,
153 },
154
155 #[error(
159 "missing required component {component_index} in element {element_index} of segment {tag}"
160 )]
161 MissingRequiredComponent {
162 tag: String,
164 element_index: usize,
166 component_index: usize,
168 },
169
170 #[error("serialized output contains invalid UTF-8")]
175 InvalidUtf8,
176
177 #[error(transparent)]
179 Io(#[from] IoError),
180
181 #[error("segment {tag} is not valid for message type {message_type}")]
186 InvalidSegmentForMessage {
187 tag: String,
189 message_type: String,
191 offset: usize,
193 },
194
195 #[error("segment {tag} has {actual} elements, expected between {min} and {max}")]
199 InvalidElementCount {
200 tag: String,
202 min: usize,
204 max: usize,
206 actual: usize,
208 offset: usize,
210 },
211
212 #[error("segment {tag} element {element_index} has {actual} components, expected {expected}")]
216 InvalidComponentCount {
217 tag: String,
219 element_index: usize,
221 expected: u8,
223 actual: u8,
225 offset: usize,
227 },
228
229 #[error(
234 "segment {tag} element {element_index}: '{value}' is not a valid code (code list {code_list})"
235 )]
236 InvalidCodeValue {
237 tag: String,
239 element_index: usize,
241 value: String,
243 code_list: String,
245 offset: usize,
247 suggestion: Option<&'static str>,
249 },
250
251 #[error("required segment {tag} is missing from message (position {expected_position})")]
255 MissingSegment {
256 tag: String,
258 expected_position: String,
260 },
261
262 #[error("segment {tag} has qualifier '{actual}', expected '{expected}'")]
266 QualifierMismatch {
267 tag: String,
269 actual: String,
271 expected: String,
273 offset: usize,
275 },
276
277 #[error("segment {tag} element {element_index}: conditional requirement not met ({condition})")]
282 ConditionalRequirementNotMet {
283 tag: String,
285 element_index: usize,
287 condition: String,
289 offset: usize,
291 },
292
293 #[error("validation failed with {error_count} error(s)")]
311 ValidationErrors {
312 error_count: usize,
314 report: Box<ValidationReport>,
316 },
317
318 #[error("segment starting at byte offset {offset} exceeded maximum length of {limit} bytes")]
327 SegmentTooLong {
328 offset: usize,
330 limit: usize,
332 },
333
334 #[error("no handler registered for message type {message_type}")]
340 UnexpectedMessageType {
341 message_type: String,
343 },
344
345 #[error("interchange too large: count {count} exceeds u32::MAX")]
352 InterchangeTooLarge {
353 count: u64,
355 },
356
357 #[error("invalid event sequence: {message}")]
365 InvalidEventSequence {
366 message: &'static str,
368 },
369
370 #[error("element definition contains invalid position 0; positions must be >= 1 (one-based)")]
376 InvalidElementPosition,
377
378 #[error("incompatible release scopes: cannot compose {current:?} with {incoming:?}")]
384 IncompatibleReleaseScopes {
385 current: String,
387 incoming: String,
389 },
390
391 #[error("segment {tag} element {element_index}: invalid field value {value:?}")]
397 InvalidFieldValue {
398 tag: String,
400 element_index: usize,
402 value: String,
404 },
405
406 #[error("unexpected data token at byte offset {offset}: data element before segment tag")]
415 UnexpectedDataToken {
416 offset: usize,
418 },
419
420 #[error(
426 "unrecognised syntax identifier '{0}': expected UNOA/UNOB/UNOC/UNOD/UNOE/UNOF (or KECA)"
427 )]
428 UnrecognisedSyntaxIdentifier(String),
429}
430
431impl From<std::io::Error> for EdifactError {
432 fn from(e: std::io::Error) -> Self {
433 Self::Io(IoError(e))
434 }
435}
436
437impl EdifactError {
438 #[must_use]
440 pub const fn stable_code(&self) -> &'static str {
441 match self {
442 Self::UnexpectedEof { .. } => "E001",
443 Self::InvalidDelimiter { .. } => "E002",
444 Self::InvalidText { .. } => "E003",
445 Self::MessageCountMismatch { .. } => "E004",
446 Self::SegmentCountMismatch { .. } => "E005",
447 Self::InvalidSegmentTag(_) => "E006",
448 Self::InvalidUna => "E007",
449 Self::MissingRequiredElement { .. } => "E008",
450 Self::InvalidUtf8 => "E009",
451 Self::Io(_) => "E010",
452 Self::InvalidSegmentForMessage { .. } => "E011",
453 Self::InvalidElementCount { .. } => "E012",
454 Self::InvalidComponentCount { .. } => "E013",
455 Self::InvalidCodeValue { .. } => "E014",
456 Self::MissingSegment { .. } => "E015",
457 Self::QualifierMismatch { .. } => "E016",
458 Self::ConditionalRequirementNotMet { .. } => "E017",
459 Self::InvalidReleaseSequence { .. } => "E019",
461 Self::SegmentTooLong { .. } => "E020",
462 Self::MissingRequiredComponent { .. } => "E021",
463 Self::UnexpectedMessageType { .. } => "E022",
464 Self::InterchangeTooLarge { .. } => "E023",
465 Self::InvalidEventSequence { .. } => "E024",
466 Self::InvalidElementPosition => "E025",
467 Self::IncompatibleReleaseScopes { .. } => "E026",
468 Self::InvalidFieldValue { .. } => "E027",
469 Self::UnexpectedDataToken { .. } => "E028",
470 Self::ValidationErrors { .. } => "E030",
473 Self::UnrecognisedSyntaxIdentifier(_) => "E031",
474 }
475 }
476
477 #[must_use]
479 pub fn recovery_hint(&self) -> Option<&'static str> {
480 match self {
481 Self::UnexpectedEof { .. } => {
482 Some("Ensure every segment ends with the configured segment terminator")
483 }
484 Self::InvalidDelimiter { .. } => {
485 Some("Check UNA service string advice and delimiter bytes in the payload")
486 }
487 Self::InvalidText { .. } => {
488 Some("Input must be valid UTF-8 text for segment and element values")
489 }
490 Self::InvalidReleaseSequence { .. } => {
491 Some("Release character must escape one following byte; trailing '?' is invalid")
492 }
493 Self::InvalidSegmentTag(_) => Some("Segment tags must be 3 ASCII uppercase letters"),
494 Self::InvalidUna => Some(
495 "UNA must be exactly 9 bytes: 'UNA' followed by 6 distinct, non-whitespace service characters",
496 ),
497 Self::MissingRequiredElement { .. } => {
498 Some("Provide all mandatory elements for the segment per directory rules")
499 }
500 Self::MissingRequiredComponent { .. } => Some(
501 "Provide all mandatory components for the composite element per directory rules",
502 ),
503 Self::InvalidSegmentForMessage { .. } => {
504 Some("Remove unsupported segment or switch to the correct message type")
505 }
506 Self::InvalidElementCount { .. } => {
507 Some("Adjust the segment element count to the allowed min/max range")
508 }
509 Self::InvalidComponentCount { .. } => {
510 Some("Fix composite element arity to match the expected component count")
511 }
512 Self::InvalidCodeValue { .. } => {
513 Some("Use a value from the referenced code list for this element")
514 }
515 Self::MissingSegment { .. } => {
516 Some("Insert the required segment at the expected position")
517 }
518 Self::QualifierMismatch { .. } => {
519 Some("Set the segment qualifier to the expected value")
520 }
521 Self::ConditionalRequirementNotMet { .. } => {
522 Some("When the condition is met, include the conditionally required element")
523 }
524 Self::SegmentTooLong { limit, .. } => {
525 let _ = limit; Some("Increase max_segment_bytes in ReaderConfig or reject the input as malformed")
527 }
528 Self::InvalidEventSequence { .. } => {
529 Some("Emit StartSegment before Element, and Element before ComponentElement")
530 }
531 Self::InvalidElementPosition => Some(
532 "Set element position to a value >= 1; positions are one-based (1 = first element slot)",
533 ),
534 Self::IncompatibleReleaseScopes { .. } => Some(
535 "Only compose ProfileRulePack values that share the same release scope, or where at most one has a release scope set",
536 ),
537 Self::InvalidFieldValue { .. } => Some(
538 "Correct the field value to match the expected format or range for this element",
539 ),
540 Self::UnexpectedDataToken { .. } => Some(
541 "A data element appeared before any segment tag; check for partial writes or encoding corruption",
542 ),
543 Self::ValidationErrors { .. }
544 | Self::MessageCountMismatch { .. }
545 | Self::SegmentCountMismatch { .. }
546 | Self::UnexpectedMessageType { .. }
547 | Self::InterchangeTooLarge { .. }
548 | Self::UnrecognisedSyntaxIdentifier(_)
549 | Self::InvalidUtf8
550 | Self::Io(_) => None,
551 }
552 }
553}
554
555#[cfg(feature = "diagnostics")]
556#[cfg_attr(docsrs, doc(cfg(feature = "diagnostics")))]
557impl miette::Diagnostic for EdifactError {
558 fn code<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
559 Some(Box::new(self.stable_code()))
560 }
561
562 fn severity(&self) -> Option<miette::Severity> {
563 match self {
564 Self::InvalidCodeValue { .. }
565 | Self::InvalidComponentCount { .. }
566 | Self::QualifierMismatch { .. } => Some(miette::Severity::Warning),
567 _ => Some(miette::Severity::Error),
568 }
569 }
570
571 fn help<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
572 match self {
573 Self::InvalidUna => Some(Box::new(
575 "UNA segment must be exactly 9 bytes: 'UNA' + 6 service characters. See EDIFACT spec",
576 )),
577 Self::InvalidUtf8 => Some(Box::new(
578 "Internal error: serialized output contains invalid UTF-8. Please report this as a bug",
579 )),
580 Self::UnexpectedEof { offset } => Some(Box::new(format!(
582 "Check that all segments are terminated with the segment terminator (usually '). \
583 Reached end at offset {offset}",
584 ))),
585 Self::InvalidDelimiter { byte, offset } => Some(Box::new(format!(
586 "The byte 0x{byte:02X} at offset {offset} is not a valid delimiter. \
587 Check UNA configuration",
588 ))),
589 Self::InvalidText { offset } => Some(Box::new(format!(
590 "The byte sequence at offset {offset} contains invalid UTF-8. \
591 Ensure input is valid UTF-8",
592 ))),
593 Self::InvalidReleaseSequence { offset } => Some(Box::new(format!(
594 "Release character at offset {offset} is dangling. \
595 Ensure '?' is followed by an escaped byte",
596 ))),
597 Self::MessageCountMismatch { expected, actual } => Some(Box::new(format!(
598 "UNZ declares {expected} message(s) but {actual} UNH/UNT pair(s) were found. \
599 Check the UNZ message count",
600 ))),
601 Self::SegmentCountMismatch {
602 expected,
603 actual,
604 message_ref,
605 } => Some(Box::new(format!(
606 "UNT for message {message_ref} declares {expected} segment(s) but {actual} were found. \
607 Check the UNT segment count",
608 ))),
609 Self::InvalidSegmentTag(tag) => Some(Box::new(format!(
610 "Segment tag '{tag}' must be exactly 3 ASCII uppercase letters",
611 ))),
612 Self::MissingRequiredElement { tag, element_index } => Some(Box::new(format!(
613 "Segment {tag} requires element at index {element_index}",
614 ))),
615 Self::MissingRequiredComponent {
616 tag,
617 element_index,
618 component_index,
619 } => Some(Box::new(format!(
620 "Segment {tag} element {element_index} requires component at index {component_index}",
621 ))),
622 Self::Io(e) => Some(Box::new(format!("I/O error: {e}"))),
623 Self::InvalidSegmentForMessage {
624 tag, message_type, ..
625 } => Some(Box::new(format!(
626 "Segment {tag} should not appear in a {message_type} message. \
627 Check the directory definition",
628 ))),
629 Self::InvalidElementCount {
630 tag,
631 min,
632 max,
633 actual,
634 ..
635 } => Some(Box::new(format!(
636 "Segment {tag} should have between {min} and {max} elements, but has {actual}. \
637 Check segment structure",
638 ))),
639 Self::InvalidComponentCount {
640 tag,
641 element_index,
642 expected,
643 actual,
644 ..
645 } => Some(Box::new(format!(
646 "In segment {tag}, element {element_index} should have {expected} components \
647 but has {actual}. Check element structure",
648 ))),
649 Self::InvalidCodeValue {
650 tag,
651 element_index,
652 value,
653 code_list,
654 ..
655 } => Some(Box::new(format!(
656 "Value '{value}' in segment {tag} element {element_index} is not in the \
657 {code_list} code list. Check the directory for valid codes",
658 ))),
659 Self::MissingSegment {
660 tag,
661 expected_position,
662 } => Some(Box::new(format!(
663 "Segment {tag} is required at position {expected_position} but is missing. \
664 Add this segment to the message",
665 ))),
666 Self::QualifierMismatch {
667 tag,
668 actual,
669 expected,
670 ..
671 } => Some(Box::new(format!(
672 "Segment {tag} has qualifier '{actual}' but expected '{expected}'. \
673 Check the segment's first component",
674 ))),
675 Self::ConditionalRequirementNotMet {
676 tag,
677 element_index,
678 condition,
679 ..
680 } => Some(Box::new(format!(
681 "In segment {tag}, element {element_index} is conditionally required when: \
682 {condition}. Check if the condition is met",
683 ))),
684 Self::SegmentTooLong { offset, limit } => Some(Box::new(format!(
685 "Segment starting at byte offset {offset} exceeds the {limit}-byte limit. \
686 Use ReaderConfig::max_segment_bytes to adjust the limit if needed, \
687 or verify the input for a missing segment terminator",
688 ))),
689 Self::UnexpectedMessageType { message_type } => Some(Box::new(format!(
690 "No handler was registered for message type '{message_type}'. \
691 Register a handler with MessageDispatch::on(\"{message_type}\", ...)",
692 ))),
693 Self::InterchangeTooLarge { count } => Some(Box::new(format!(
694 "Interchange contains {count} items which exceeds the u32::MAX limit. \
695 This is an extremely unusual input; verify the message is not corrupted.",
696 ))),
697 Self::InvalidEventSequence { message } => Some(Box::new(format!(
698 "Event sequence violation: {message}. \
699 Check that StartSegment is emitted before Element, and Element before ComponentElement.",
700 ))),
701 Self::InvalidElementPosition => Some(Box::new(
702 "Element positions must be >= 1 (one-based). \
703 Ensure no OwnedElementRef is constructed with position == 0",
704 )),
705 Self::IncompatibleReleaseScopes { current, incoming } => Some(Box::new(format!(
706 "Release scope {current:?} and {incoming:?} are incompatible. \
707 Only compose ProfileRulePack values that share the same release scope, \
708 or where at most one carries a release scope",
709 ))),
710 Self::InvalidFieldValue {
711 tag,
712 element_index,
713 value,
714 } => Some(Box::new(format!(
715 "Segment {tag} element {element_index} has invalid value '{value}'. \
716 Check the expected format or range for this field",
717 ))),
718 Self::UnexpectedDataToken { offset } => Some(Box::new(format!(
719 "Data element at offset {offset} appeared before any segment tag. \
720 Check for partial writes or encoding corruption",
721 ))),
722 Self::ValidationErrors { error_count, .. } => Some(Box::new(format!(
723 "Validation found {error_count} error(s). Inspect the ValidationReport for details",
724 ))),
725 Self::UnrecognisedSyntaxIdentifier(id) => Some(Box::new(format!(
726 "Syntax identifier '{id}' is not defined in ISO 9735-1. \
727 Valid values are UNOA, UNOB, UNOC, UNOD, UNOE, UNOF (or KECA for KEC-A profile)",
728 ))),
729 }
730 }
731}
732
733pub use crate::report::ValidationReport;
736
737#[cfg(test)]
738mod tests {
739 use super::*;
740
741 #[test]
742 fn recovery_hint_exists_for_common_malformed_cases() {
743 let err = EdifactError::InvalidReleaseSequence { offset: 10 };
744 assert!(err.recovery_hint().is_some());
745
746 let err = EdifactError::InvalidCodeValue {
747 tag: "BGM".to_owned(),
748 element_index: 0,
749 value: "X".to_owned(),
750 code_list: "1001".to_owned(),
751 offset: 0,
752 suggestion: None,
753 };
754 assert!(err.recovery_hint().is_some());
755 }
756}