Skip to main content

fints_client/
error.rs

1use serde::{Deserialize, Serialize};
2use thiserror::Error;
3
4use crate::return_code::{Category, ReturnCode};
5
6// The types `FinTSError::SegmentUnreadable` carries, nameable without the
7// `tooling` feature (which makes the whole `codec` module public).
8pub use crate::codec::{CodecError, ErrorKind, SegmentId, WireError, WireErrorKind};
9
10/// Errors that can occur during FinTS operations.
11#[derive(Error, Debug)]
12pub enum FinTSError {
13    #[error("Parse error: {0}")]
14    Parse(String),
15
16    #[error("Serialization error: {0}")]
17    Serialize(String),
18
19    /// The message did not reach the bank or the answer could not be read
20    /// back; `kind` says which step failed. A request timeout is
21    /// [`FinTSError::Timeout`] and an HTTP status [`FinTSError::Http`].
22    #[error("Transport error ({kind}): {message}")]
23    Transport {
24        kind: TransportKind,
25        message: String,
26    },
27
28    /// An HTTP request did not finish within the transport's timeout.
29    #[error("Request timed out")]
30    Timeout,
31
32    #[error("HTTP error (status {status}): {message}")]
33    Http { status: u16, message: String },
34
35    #[error("Dialog error: {0}")]
36    Dialog(String),
37
38    /// The bank rejected the message or an order (a class 9 code): the
39    /// selected code line plus every code of the response. Its category
40    /// says what to do ([`BankError::category`]).
41    #[error("{0}")]
42    Bank(BankError),
43
44    /// No version of the order is both offered by the bank (BPD) and
45    /// implemented by this client (Formals C.10). Names both sides. A
46    /// client-side check before anything is sent.
47    #[error("{0}")]
48    VersionMismatch(crate::protocol::VersionMismatch),
49
50    /// Stored state (session state) carries another format tag than this
51    /// version reads, older or newer. There is no migration: start from an
52    /// empty state.
53    #[error("stored state has format {found:?}; this version reads {expected:?}")]
54    StateFormat {
55        found: String,
56        expected: &'static str,
57    },
58
59    /// A paused dialog was thawed with a client or credentials it was not
60    /// frozen with (`field`: `blz`, `url` or `user_id`). Nothing was sent.
61    #[error("paused dialog belongs to another {field}")]
62    PausedDialogMismatch { field: &'static str },
63
64    /// An order was built without bank parameter data. Orders only run in
65    /// a dialog opened after synchronisation, so there is no version to
66    /// choose and none is guessed.
67    #[error("{code}: no bank parameter data (BPD) known; synchronise first")]
68    NoBpd { code: crate::types::SegmentType },
69
70    /// The negotiated version of an order cannot address this account
71    /// (national vs. international account details, Messages B.3). No
72    /// lower version is tried.
73    #[error("{code} v{version} cannot address this account: {reason}")]
74    AccountNotAddressable {
75        code: crate::types::SegmentType,
76        version: u16,
77        reason: AddressingReason,
78    },
79
80    /// A bug in this client, for example a segment version it claims to
81    /// implement but cannot build.
82    #[error("Internal error: {0}")]
83    Internal(String),
84
85    #[error("Invalid response from bank: {0}")]
86    InvalidResponse(String),
87
88    /// A received segment that matters for the dialog (HITAN) was rejected
89    /// by its codec definition; carries the segment, field and rule.
90    #[error("Unreadable segment from bank: {0}")]
91    SegmentUnreadable(crate::codec::CodecError),
92
93    #[error("MT940 parse error: {0}")]
94    Mt940(String),
95
96    #[error("CAMT parse error: {0}")]
97    Camt(String),
98    /// The payee check report (pain.002) the bank sent could not be read.
99    /// The raw document is in the trace; no result is guessed.
100    #[error("pain.002 error: {0}")]
101    Pain002(String),
102    /// The transfer the caller described cannot be sent: a field breaks a
103    /// rule (SEPA charset, length, IBAN, BIC, amount). Nothing was sent;
104    /// fix the data and retry.
105    #[error("invalid transfer: {0}")]
106    InvalidTransfer(#[from] crate::jobs::InvalidTransfer),
107
108    /// After a message carried a payment order or its TAN, the bank's
109    /// decision is unknown: a transport error, an unreadable answer
110    /// (HIRMS, HITAN, HIVPP, pain.002), an answer that fits no case, a
111    /// decoupled approval past the bank's `max_polls`, or a future the
112    /// caller dropped mid-request (reported once, by the next call on the
113    /// dialog). Every error after the order but a class 9 rejection is
114    /// this one. The bank may or may not execute the payment. Check the
115    /// account (by `end_to_end_id`, pain.001 `message_id`) before trying
116    /// again; the library never resends. The dialog has ended when the
117    /// message number is unknown.
118    #[error(
119        "payment outcome unknown (end-to-end ID {end_to_end_id}, message ID {message_id}): check the account before trying again"
120    )]
121    PaymentOutcomeUnknown {
122        end_to_end_id: String,
123        message_id: String,
124    },
125
126    /// The bank's maximum of decoupled status requests is used up (a
127    /// read or the login; a transfer gets
128    /// [`FinTSError::PaymentOutcomeUnknown`]).
129    #[error("Decoupled TAN: bank's maximum of {0} status requests reached")]
130    DecoupledMaxPolls(u32),
131
132    /// A job was started while the dialog waits for a TAN or decoupled
133    /// confirmation of another one: resume (`submit_tan`, `poll`) or
134    /// `cancel` that job first. Nothing was sent.
135    #[error("the dialog is paused on a TAN step of another job")]
136    DialogPaused,
137
138    /// The resume ticket does not belong to the job this dialog waits for
139    /// (another task reference or job, or no job pending). Nothing was
140    /// sent.
141    #[error("resume ticket does not match the dialog's pending job")]
142    WrongResume,
143
144    /// The dialog is over: the bank ended it (9800), a transport error or a
145    /// dropped request left its message number unknown, or its login
146    /// failed. Open a new dialog.
147    #[error("the dialog has ended; open a new one")]
148    DialogEnded,
149
150    #[error("IO error: {0}")]
151    Io(#[from] std::io::Error),
152}
153
154impl FinTSError {
155    /// A [`FinTSError::Transport`] of `kind`.
156    pub fn transport(kind: TransportKind, message: impl Into<String>) -> Self {
157        Self::Transport {
158            kind,
159            message: message.into(),
160        }
161    }
162
163    /// What the caller can do about this error. Bank errors take the
164    /// category of their selected code; client-side errors have a fixed
165    /// one.
166    pub fn kind(&self) -> Category {
167        match self {
168            Self::Bank(e) => e.category(),
169            Self::Transport { .. } | Self::Timeout | Self::Io(_) => Category::Temporary,
170            Self::Http { status, .. } if *status >= 500 || *status == 408 || *status == 429 => {
171                Category::Temporary
172            }
173            Self::Http { .. } => Category::Rejected,
174            Self::DecoupledMaxPolls(_) => Category::Tan,
175            Self::VersionMismatch(_) | Self::AccountNotAddressable { .. } => Category::Unsupported,
176            Self::DialogEnded => Category::DialogEnded,
177            Self::InvalidTransfer(_) => Category::InvalidInput,
178            Self::PaymentOutcomeUnknown { .. } => Category::OutcomeUnknown,
179            Self::Parse(_)
180            | Self::DialogPaused
181            | Self::WrongResume
182            | Self::Serialize(_)
183            | Self::Dialog(_)
184            | Self::NoBpd { .. }
185            | Self::StateFormat { .. }
186            | Self::PausedDialogMismatch { .. }
187            | Self::Internal(_)
188            | Self::InvalidResponse(_)
189            | Self::SegmentUnreadable(_)
190            | Self::Mt940(_)
191            | Self::Camt(_)
192            | Self::Pain002(_) => Category::ClientFault,
193        }
194    }
195
196    /// The bank error, if this is one.
197    pub fn bank_error(&self) -> Option<&BankError> {
198        match self {
199            Self::Bank(e) => Some(e),
200            _ => None,
201        }
202    }
203
204    /// Whether the bank refused the login data or has blocked the access.
205    /// Do not repeat the request automatically: each attempt with a wrong
206    /// PIN counts, and after a few the bank blocks the access until the
207    /// customer has it unblocked.
208    pub fn is_credentials_error(&self) -> bool {
209        matches!(self.kind(), Category::Credentials(_))
210    }
211
212    /// Whether only the customer can resolve this: a TAN is wanted, or an
213    /// approval in the app did not come in time. Ask the customer before
214    /// trying again.
215    pub fn needs_user(&self) -> bool {
216        self.kind() == Category::Tan
217    }
218
219    /// A temporary failure worth retrying later unchanged: network trouble,
220    /// timeouts, server errors, rate limiting, a bank system that is
221    /// briefly unavailable.
222    pub fn is_retryable(&self) -> bool {
223        self.kind() == Category::Temporary
224    }
225}
226
227/// Which step of a transport exchange failed ([`FinTSError::Transport`]).
228/// [`FinTSError::kind`] reports every transport error as
229/// [`Category::Temporary`]; [`TransportKind::is_retryable`] tells a
230/// certificate problem (`Tls`), which a retry does not fix, from a network
231/// blip.
232#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
233#[serde(rename_all = "snake_case")]
234#[non_exhaustive]
235pub enum TransportKind {
236    /// The host name did not resolve.
237    Dns,
238    /// The connection was refused, reset or unreachable before TLS.
239    Connect,
240    /// The TLS handshake failed (certificate, protocol, alert). A retry
241    /// without a change of trust store or bank URL fails again.
242    Tls,
243    /// Another failure while sending the request or reading the answer.
244    Io,
245    /// The answer arrived but is not the base64 the transport expects.
246    Decode,
247    /// The transport cannot work as configured (no HTTP client; feature
248    /// `http` off and no transport set).
249    Config,
250}
251
252impl TransportKind {
253    /// Stable lower-case name (`dns`, `connect`, `tls`, `io`, `decode`,
254    /// `config`).
255    pub fn as_str(self) -> &'static str {
256        match self {
257            Self::Dns => "dns",
258            Self::Connect => "connect",
259            Self::Tls => "tls",
260            Self::Io => "io",
261            Self::Decode => "decode",
262            Self::Config => "config",
263        }
264    }
265
266    /// Whether the same request may work later without a change.
267    pub fn is_retryable(self) -> bool {
268        !matches!(self, Self::Tls | Self::Config)
269    }
270}
271
272impl std::fmt::Display for TransportKind {
273    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
274        f.write_str(self.as_str())
275    }
276}
277
278/// A rejection by the bank: the code line selected as the reason
279/// (docs/return-codes-design.md section 3) and every code of the response,
280/// in wire order (HIRMG first, then HIRMS), so nothing is lost.
281#[derive(Debug, Clone, PartialEq, Eq)]
282pub struct BankError(Box<BankErrorInner>);
283
284#[derive(Debug, Clone, PartialEq, Eq)]
285struct BankErrorInner {
286    code: ReturnCode,
287    codes: Vec<ReturnCode>,
288}
289
290impl BankError {
291    /// `code` is the selected class 9 code, `codes` all codes of the
292    /// response.
293    pub fn new(code: ReturnCode, codes: Vec<ReturnCode>) -> Self {
294        Self(Box::new(BankErrorInner { code, codes }))
295    }
296
297    /// The code line reported as the reason.
298    pub fn code(&self) -> &ReturnCode {
299        &self.0.code
300    }
301
302    /// Every code of the response, success and warning codes included.
303    pub fn codes(&self) -> &[ReturnCode] {
304        &self.0.codes
305    }
306
307    /// What the caller can do, from the selected code.
308    pub fn category(&self) -> Category {
309        self.0.code.category().unwrap_or(Category::Rejected)
310    }
311}
312
313impl std::fmt::Display for BankError {
314    /// `Bank error 9210: Keine gueltige Kontoverbindung`
315    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
316        write!(f, "Bank error {}", self.0.code)
317    }
318}
319
320/// Why an order version cannot address an account
321/// ([`FinTSError::AccountNotAddressable`]).
322#[derive(Debug, Clone, Copy, PartialEq, Eq)]
323#[non_exhaustive]
324pub enum AddressingReason {
325    /// The version addresses accounts nationally (ktv), but the account has
326    /// no account number and BLZ and none can be derived from its IBAN.
327    NoNationalDetails,
328    /// The version addresses accounts by IBAN and BIC (kti), but the account
329    /// has none.
330    NoIbanBic,
331}
332
333impl std::fmt::Display for AddressingReason {
334    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
335        f.write_str(match self {
336            Self::NoNationalDetails => {
337                "it needs a national account number and BLZ, which cannot be derived \
338                 from the IBAN; use Account::with_national()"
339            }
340            Self::NoIbanBic => "it needs an IBAN and BIC, which the account lacks",
341        })
342    }
343}
344
345pub type Result<T> = std::result::Result<T, FinTSError>;
346
347#[cfg(test)]
348mod tests {
349    use super::*;
350    use crate::return_code::{Code, Scope};
351
352    fn bank(code: &str) -> FinTSError {
353        let c = ReturnCode::new(Code::new(code).unwrap(), "t", Scope::Message);
354        FinTSError::Bank(BankError::new(c.clone(), vec![c]))
355    }
356
357    /// Every error has a category; the predicates follow from it.
358    #[test]
359    fn classification() {
360        use crate::return_code::Credentials;
361        let http = |status| FinTSError::Http {
362            status,
363            message: "m".into(),
364        };
365        let cases: Vec<(FinTSError, Category)> = vec![
366            (bank("9942"), Category::Credentials(Credentials::PinWrong)),
367            (bank("9931"), Category::Credentials(Credentials::Locked)),
368            (bank("9910"), Category::Credentials(Credentials::Unclear)),
369            (bank("9391"), Category::SystemId),
370            (bank("9941"), Category::Tan),
371            (bank("9000"), Category::OutcomeUnknown),
372            (bank("9311"), Category::Temporary),
373            (bank("9210"), Category::Rejected),
374            (FinTSError::DecoupledMaxPolls(3), Category::Tan),
375            (
376                FinTSError::transport(TransportKind::Io, "reset"),
377                Category::Temporary,
378            ),
379            (FinTSError::Timeout, Category::Temporary),
380            (http(503), Category::Temporary),
381            (http(408), Category::Temporary),
382            (http(429), Category::Temporary),
383            (http(404), Category::Rejected),
384            (FinTSError::DialogPaused, Category::ClientFault),
385            (FinTSError::WrongResume, Category::ClientFault),
386            (FinTSError::DialogEnded, Category::DialogEnded),
387            (
388                FinTSError::PausedDialogMismatch { field: "blz" },
389                Category::ClientFault,
390            ),
391            (FinTSError::Internal("x".into()), Category::ClientFault),
392            (
393                FinTSError::InvalidResponse("x".into()),
394                Category::ClientFault,
395            ),
396            (
397                FinTSError::NoBpd {
398                    code: crate::types::SegmentType::new("HKSAL"),
399                },
400                Category::ClientFault,
401            ),
402            (
403                FinTSError::AccountNotAddressable {
404                    code: crate::types::SegmentType::new("HKSAL"),
405                    version: 4,
406                    reason: AddressingReason::NoIbanBic,
407                },
408                Category::Unsupported,
409            ),
410        ];
411        for (err, want) in &cases {
412            assert_eq!(err.kind(), *want, "{err}");
413            assert_eq!(
414                err.is_credentials_error(),
415                matches!(want, Category::Credentials(_)),
416                "{err}"
417            );
418            assert_eq!(err.needs_user(), *want == Category::Tan, "{err}");
419            assert_eq!(err.is_retryable(), *want == Category::Temporary, "{err}");
420        }
421        assert_eq!(bank("9210").to_string(), "Bank error 9210: t");
422    }
423
424    /// Categories and transport kinds go over a wire as stable snake_case
425    /// strings; credentials carry their reason.
426    #[test]
427    fn category_and_transport_kind_serialize() {
428        use crate::return_code::Credentials;
429        let json = |c: Category| serde_json::to_string(&c).unwrap();
430        assert_eq!(json(Category::Temporary), "\"temporary\"");
431        assert_eq!(json(Category::DialogEnded), "\"dialog_ended\"");
432        assert_eq!(
433            json(Category::Credentials(Credentials::PinWrong)),
434            "{\"credentials\":\"pin_wrong\"}"
435        );
436        for c in [
437            Category::Tan,
438            Category::OutcomeUnknown,
439            Category::Credentials(Credentials::Locked),
440        ] {
441            assert_eq!(serde_json::from_str::<Category>(&json(c)).unwrap(), c);
442        }
443        for (k, s) in [
444            (TransportKind::Dns, "dns"),
445            (TransportKind::Connect, "connect"),
446            (TransportKind::Tls, "tls"),
447            (TransportKind::Io, "io"),
448            (TransportKind::Decode, "decode"),
449            (TransportKind::Config, "config"),
450        ] {
451            assert_eq!(serde_json::to_string(&k).unwrap(), format!("\"{s}\""));
452            assert_eq!(k.as_str(), s);
453        }
454        assert!(TransportKind::Dns.is_retryable() && !TransportKind::Tls.is_retryable());
455    }
456}