Skip to main content

fints_client/codec/
error.rs

1//! Typed codec errors: which segment, which position, which rule.
2
3use std::fmt;
4
5/// Where in a message the tokenizer failed (byte offset into the input).
6#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
7#[error("wire syntax error at byte {offset}: {kind}")]
8pub struct WireError {
9    /// Byte offset into the tokenized input.
10    pub offset: usize,
11    pub kind: WireErrorKind,
12}
13
14/// A violation of the FinTS syntax rules (Formals H.1).
15#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
16#[non_exhaustive]
17pub enum WireErrorKind {
18    /// Input ends inside a segment: no segment end character `'` (H.1.2).
19    #[error("segment not terminated by '")]
20    UnterminatedSegment,
21    /// Input ends right after the release character `?` (H.1.3).
22    #[error("release character ? at end of input")]
23    DanglingEscape,
24    /// `@` not followed by `<digits>@` (H.1.4).
25    #[error("malformed binary length")]
26    BadBinaryLength,
27    /// The binary length points past the end of the input (H.1.4).
28    #[error("binary data of {declared} bytes runs past the end of the input")]
29    BinaryOverrun { declared: usize },
30    /// Binary data starts after other characters of the same element.
31    #[error("binary marker @ inside a text element")]
32    BinaryInsideText,
33    /// Something other than a separator follows binary data.
34    #[error("binary data not followed by a separator")]
35    DataAfterBinary,
36}
37
38/// A rule broken by a value, found while parsing or serialising.
39#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
40#[non_exhaustive]
41pub enum ErrorKind {
42    /// A mandatory element is empty or absent (Formals B.3.1, status M).
43    #[error("mandatory element missing")]
44    Missing,
45    /// Longer than the maximum length (B.3.3, `..n`), counted before escaping.
46    #[error("too long: {actual} bytes, at most {max} allowed")]
47    TooLong { max: usize, actual: usize },
48    /// Not the fixed length (B.3.3).
49    #[error("wrong length: {actual} bytes, exactly {expected} required")]
50    WrongLength { expected: usize, actual: usize },
51    /// A character the format does not allow (B.4).
52    #[error("character {found:?} not allowed in format {format}")]
53    InvalidCharacter { format: &'static str, found: char },
54    /// A character outside ISO 8859-1 (B.1); cannot be put on the wire.
55    #[error("character {found:?} is outside ISO 8859-1")]
56    NotLatin1 { found: char },
57    /// `num`/`float` with a leading zero (B.4.1).
58    #[error("leading zero not allowed in format {format}")]
59    LeadingZero { format: &'static str },
60    /// A number that does not fit the Rust type behind the element.
61    #[error("number too large")]
62    NumberTooLarge,
63    /// Not a valid `dat` (B.4.2: JJJJMMTT, an existing date).
64    #[error("not a valid date (JJJJMMTT)")]
65    InvalidDate,
66    /// Not a valid `tim` (B.4.2: hhmmss, a valid time).
67    #[error("not a valid time (hhmmss)")]
68    InvalidTime,
69    /// Not `J` or `N` (B.4.2, `jn`).
70    #[error("expected J or N")]
71    InvalidYesNo,
72    /// Not a valid `float`/`wrt` value (B.4.1: decimal comma obligatory).
73    #[error("not a valid value with decimal comma")]
74    InvalidValue,
75    /// Binary data where the format is text.
76    #[error("binary data where text was expected")]
77    ExpectedText,
78    /// Text where the format is `bin` (H.1.4).
79    #[error("text where binary data was expected")]
80    ExpectedBinary,
81    /// Fewer repetitions than the minimum count (B.3.1).
82    #[error("{actual} repetitions, at least {min} required")]
83    TooFewRepetitions { min: usize, actual: usize },
84    /// More repetitions than the maximum count (B.3.1).
85    #[error("{actual} repetitions, at most {max} allowed")]
86    TooManyRepetitions { max: usize, actual: usize },
87    /// Non-empty elements after the last element the definition knows.
88    #[error("unexpected data after the last defined element")]
89    UnexpectedData,
90    /// The segment header (`code:number:version[:reference]`) is malformed.
91    #[error("malformed segment header: {0}")]
92    InvalidHeader(String),
93    /// The segment is a different code or version than the definition.
94    #[error("expected segment {expected_code} v{expected_version}")]
95    WrongSegment {
96        expected_code: &'static str,
97        expected_version: u16,
98    },
99    /// No definition for this code and version is registered.
100    #[error("no definition for this segment code and version")]
101    UnknownSegment,
102    /// The message could not be tokenized.
103    #[error(transparent)]
104    Wire(#[from] WireError),
105}
106
107/// The segment an error belongs to, as read from its header.
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct SegmentId {
110    pub code: String,
111    pub version: u16,
112    /// Segment number from the header (position in the message).
113    pub number: u16,
114}
115
116/// A codec error with its location.
117///
118/// `de` counts data elements of the segment from 1, the segment header being
119/// DE 1, as the "Nr." column of the specification tables does. `element`
120/// counts the group data elements (GD) inside that DE from 1, after nested
121/// groups are flattened, which is the colon-separated position on the wire.
122/// `field` is the Rust field path, e.g. `parameters.methods[2].name`.
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct CodecError {
125    pub segment: Option<SegmentId>,
126    pub de: Option<usize>,
127    pub element: Option<usize>,
128    pub field: String,
129    pub kind: ErrorKind,
130}
131
132impl CodecError {
133    /// A new error without location.
134    pub fn new(kind: ErrorKind) -> Self {
135        CodecError {
136            segment: None,
137            de: None,
138            element: None,
139            field: String::new(),
140            kind,
141        }
142    }
143
144    /// Prepends a field name to the field path.
145    pub fn in_field(mut self, name: &str) -> Self {
146        if self.field.is_empty() {
147            self.field = name.to_string();
148        } else if self.field.starts_with('[') {
149            self.field = format!("{name}{}", self.field);
150        } else {
151            self.field = format!("{name}.{}", self.field);
152        }
153        self
154    }
155
156    /// Prepends a repetition index to the field path.
157    pub fn in_index(mut self, index: usize) -> Self {
158        if self.field.is_empty() || self.field.starts_with('[') {
159            self.field = format!("[{index}]{}", self.field);
160        } else {
161            self.field = format!("[{index}].{}", self.field);
162        }
163        self
164    }
165
166    /// Sets the 1-based group element position unless already set.
167    pub fn at_element(mut self, element: usize) -> Self {
168        self.element.get_or_insert(element);
169        self
170    }
171
172    /// Sets the 1-based data element position unless already set.
173    pub fn at_de(mut self, de: usize) -> Self {
174        self.de.get_or_insert(de);
175        self
176    }
177
178    /// Sets the segment unless already set.
179    pub fn in_segment(mut self, id: SegmentId) -> Self {
180        self.segment.get_or_insert(id);
181        self
182    }
183}
184
185impl From<ErrorKind> for CodecError {
186    fn from(kind: ErrorKind) -> Self {
187        CodecError::new(kind)
188    }
189}
190
191impl From<WireError> for CodecError {
192    fn from(e: WireError) -> Self {
193        CodecError::new(ErrorKind::Wire(e))
194    }
195}
196
197impl fmt::Display for CodecError {
198    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199        if let Some(seg) = &self.segment {
200            write!(f, "{} v{} (segment {})", seg.code, seg.version, seg.number)?;
201        } else {
202            f.write_str("segment")?;
203        }
204        if let Some(de) = self.de {
205            write!(f, ", DE {de}")?;
206        }
207        if let Some(el) = self.element {
208            write!(f, ", element {el}")?;
209        }
210        if !self.field.is_empty() {
211            write!(f, " ({})", self.field)?;
212        }
213        write!(f, ": {}", self.kind)
214    }
215}
216
217impl std::error::Error for CodecError {
218    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
219        match &self.kind {
220            ErrorKind::Wire(e) => Some(e),
221            _ => None,
222        }
223    }
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229
230    #[test]
231    fn field_paths_compose_from_the_inside_out() {
232        let e = CodecError::new(ErrorKind::Missing)
233            .in_field("name")
234            .in_index(2)
235            .in_field("methods")
236            .in_field("parameters");
237        assert_eq!(e.field, "parameters.methods[2].name");
238    }
239
240    #[test]
241    fn display_names_segment_position_field_and_rule() {
242        let e = CodecError::new(ErrorKind::TooLong {
243            max: 30,
244            actual: 31,
245        })
246        .at_element(12)
247        .in_field("name")
248        .at_de(5)
249        .in_segment(SegmentId {
250            code: "HITANS".into(),
251            version: 6,
252            number: 4,
253        });
254        assert_eq!(
255            e.to_string(),
256            "HITANS v6 (segment 4), DE 5, element 12 (name): too long: 31 bytes, at most 30 allowed"
257        );
258    }
259}