1use serde::{Deserialize, Serialize};
2use thiserror::Error;
3
4use crate::return_code::{Category, ReturnCode};
5
6pub use crate::codec::{CodecError, ErrorKind, SegmentId, WireError, WireErrorKind};
9
10#[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 #[error("Transport error ({kind}): {message}")]
23 Transport {
24 kind: TransportKind,
25 message: String,
26 },
27
28 #[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 #[error("{0}")]
42 Bank(BankError),
43
44 #[error("{0}")]
48 VersionMismatch(crate::protocol::VersionMismatch),
49
50 #[error("stored state has format {found:?}; this version reads {expected:?}")]
54 StateFormat {
55 found: String,
56 expected: &'static str,
57 },
58
59 #[error("paused dialog belongs to another {field}")]
62 PausedDialogMismatch { field: &'static str },
63
64 #[error("{code}: no bank parameter data (BPD) known; synchronise first")]
68 NoBpd { code: crate::types::SegmentType },
69
70 #[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 #[error("Internal error: {0}")]
83 Internal(String),
84
85 #[error("Invalid response from bank: {0}")]
86 InvalidResponse(String),
87
88 #[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 #[error("pain.002 error: {0}")]
101 Pain002(String),
102 #[error("invalid transfer: {0}")]
106 InvalidTransfer(#[from] crate::jobs::InvalidTransfer),
107
108 #[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 #[error("Decoupled TAN: bank's maximum of {0} status requests reached")]
130 DecoupledMaxPolls(u32),
131
132 #[error("the dialog is paused on a TAN step of another job")]
136 DialogPaused,
137
138 #[error("resume ticket does not match the dialog's pending job")]
142 WrongResume,
143
144 #[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 pub fn transport(kind: TransportKind, message: impl Into<String>) -> Self {
157 Self::Transport {
158 kind,
159 message: message.into(),
160 }
161 }
162
163 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 pub fn bank_error(&self) -> Option<&BankError> {
198 match self {
199 Self::Bank(e) => Some(e),
200 _ => None,
201 }
202 }
203
204 pub fn is_credentials_error(&self) -> bool {
209 matches!(self.kind(), Category::Credentials(_))
210 }
211
212 pub fn needs_user(&self) -> bool {
216 self.kind() == Category::Tan
217 }
218
219 pub fn is_retryable(&self) -> bool {
223 self.kind() == Category::Temporary
224 }
225}
226
227#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
233#[serde(rename_all = "snake_case")]
234#[non_exhaustive]
235pub enum TransportKind {
236 Dns,
238 Connect,
240 Tls,
243 Io,
245 Decode,
247 Config,
250}
251
252impl TransportKind {
253 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 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#[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 pub fn new(code: ReturnCode, codes: Vec<ReturnCode>) -> Self {
294 Self(Box::new(BankErrorInner { code, codes }))
295 }
296
297 pub fn code(&self) -> &ReturnCode {
299 &self.0.code
300 }
301
302 pub fn codes(&self) -> &[ReturnCode] {
304 &self.0.codes
305 }
306
307 pub fn category(&self) -> Category {
309 self.0.code.category().unwrap_or(Category::Rejected)
310 }
311}
312
313impl std::fmt::Display for BankError {
314 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
316 write!(f, "Bank error {}", self.0.code)
317 }
318}
319
320#[derive(Debug, Clone, Copy, PartialEq, Eq)]
323#[non_exhaustive]
324pub enum AddressingReason {
325 NoNationalDetails,
328 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 #[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 #[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}