Skip to main content

client_parse/
client_parse.rs

1//! Parse a SNAP BI response from the wire, classify error responses into
2//! typed [`Error`] variants, and dispatch on [`Category`].
3//!
4//! Demonstrates the recommended client-side path post v2.0:
5//!
6//! 1. Deserialise with the consumer's typed payload `T`.
7//! 2. Inspect `envelope.response_code` defensively — malformed codes do not
8//!    blow up the parse; `.raw()` is always available.
9//! 3. Map back to a typed [`Error`] variant via [`ResponseCode::classify`] and
10//!    decide retry policy from [`Error::category`].
11
12use kamu_snap_response::{Category, SnapResponse};
13use serde::Deserialize;
14
15#[derive(Debug, Deserialize)]
16struct BalancePayload {
17    #[serde(rename = "accountNo")]
18    account_no: String,
19    #[serde(rename = "currentBalance")]
20    current_balance: String,
21}
22
23fn main() -> Result<(), Box<dyn std::error::Error>> {
24    let wires = [
25        r#"{"responseCode":"2001100","responseMessage":"Successful","accountNo":"1234","currentBalance":"99000.00"}"#,
26        r#"{"responseCode":"4011100","responseMessage":"Unauthorized. Invalid token"}"#,
27        r#"{"responseCode":"4031114","responseMessage":"Insufficient Funds"}"#,
28        // BRI's 6-digit source-doc defect — still parseable, raw preserved.
29        r#"{"responseCode":"500000","responseMessage":"General Error"}"#,
30    ];
31
32    for wire in wires {
33        println!("---");
34        println!("wire: {wire}");
35
36        let resp: SnapResponse<BalancePayload> = serde_json::from_str(wire)?;
37        println!("raw responseCode: {}", resp.envelope.response_code.raw());
38
39        match resp.envelope.response_code.classify() {
40            Some(err) => {
41                println!("classified error: {err}");
42                println!("category: {}", err.category());
43                let action = match err.category() {
44                    Category::Business => "do NOT retry (business rule violation)",
45                    Category::System => "retry with backoff",
46                    Category::Message => "fix client request before retry",
47                    Category::Success => "no action",
48                    _ => "review manually",
49                };
50                println!("policy: {action}");
51            }
52            None => {
53                if let Some(payload) = resp.payload() {
54                    println!("success! account {} balance {}", payload.account_no, payload.current_balance);
55                } else {
56                    println!("unrecognized code with no payload — log and escalate");
57                }
58            }
59        }
60    }
61    Ok(())
62}