Skip to main content

ResponseCode

Struct ResponseCode 

Source
pub struct ResponseCode(/* private fields */);
Expand description

Wire-format responseCode.

Construct via ResponseCode::parse (defensive — never fails) or via ResponseCode::from_parts (validated). The raw string is preserved verbatim even when malformed.

Implementations§

Source§

impl ResponseCode

Source

pub fn parse(s: impl Into<String>) -> Self

Wrap an arbitrary string. Never fails — the value is preserved as-is.

Source

pub fn from_parts(http: u16, service: ServiceCode, case: u8) -> Self

Construct from validated (http, service, case) parts. Panics if http is outside 100..=999 or case is outside 0..=99 — either would widen the canonical 7-digit HHHSSCC wire form (e.g. case = 100 formats as three digits, yielding an 8-char code that every reader then rejects). Use ResponseCode::parse when you cannot guarantee the inputs.

Source

pub fn success(service: ServiceCode, sub: u8) -> Self

Construct a 2-prefix success code (2HH SSCC with HH=00).

Source

pub fn raw(&self) -> &str

The verbatim wire string.

Examples found in repository?
examples/client_parse.rs (line 37)
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}
Source

pub fn http(&self) -> Option<StatusCode>

Extract the leading HTTP status, defensively. None if the code is not in the canonical 7-digit form or the leading 3 digits don’t form a valid HTTP status.

Source

pub fn service(&self) -> Option<ServiceCode>

Extract the service code (positions 4..5). None for malformed codes.

Source

pub fn case(&self) -> Option<u8>

Extract the case code (positions 6..7). None for malformed codes.

Source

pub fn classify(&self) -> Option<Error>

Inverse classifier: given a received wire code, return the matching Error variant (with empty-string payload where the variant carries one). None for unknown HTTP+case pairs and for malformed wire forms.

Designed for client-side use — receiving a response and reasoning about it typed.

Examples found in repository?
examples/client_parse.rs (line 39)
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}

Trait Implementations§

Source§

impl Clone for ResponseCode

Source§

fn clone(&self) -> ResponseCode

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ResponseCode

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for ResponseCode

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for ResponseCode

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for ResponseCode

Source§

impl Hash for ResponseCode

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for ResponseCode

Source§

fn eq(&self, other: &ResponseCode) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for ResponseCode

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for ResponseCode

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V