razorpay_api/error.rs
1use reqwest::StatusCode;
2use serde::Deserialize;
3
4/// Everything that can go wrong in this crate.
5///
6/// The variants are kept distinct so retry logic can be written correctly — see
7/// [`is_retryable`](RazorpayError::is_retryable).
8#[derive(Debug, thiserror::Error)]
9#[non_exhaustive]
10pub enum RazorpayError {
11 /// The request never completed — DNS, TLS, connection, or timeout failure.
12 ///
13 /// Usually transient, so generally safe to retry for idempotent calls.
14 #[error("http error: {0}")]
15 Http(#[from] reqwest::Error),
16
17 /// Razorpay returned a structured error.
18 ///
19 /// Boxed because it is by far the largest variant; inline it would put ~150
20 /// bytes on every `Result` the crate returns, including the overwhelmingly
21 /// common success path.
22 #[error("api error [{code}]: {description}", code = .0.code, description = .0.description)]
23 Api(Box<ApiError>),
24
25 /// A non-2xx response that carried no parseable error envelope.
26 ///
27 /// Typically a gateway or proxy failure returning HTML rather than JSON. The
28 /// raw body is preserved instead of being reported as a misleading decode error.
29 #[error("unexpected http status {http_status}: {body}")]
30 UnexpectedStatus {
31 /// The HTTP status returned.
32 http_status: StatusCode,
33 /// The raw response body.
34 body: String,
35 },
36
37 /// A request path could not be joined onto the base URL.
38 #[error("invalid url: {0}")]
39 InvalidUrl(String),
40
41 /// A payment or webhook signature did not match.
42 ///
43 /// Treat this as a forgery attempt: do not fulfil the order.
44 #[error("signature verification failed")]
45 SignatureMismatch,
46
47 /// The response was not the shape this crate expected.
48 ///
49 /// Means an API change or a bug in our types — never retryable, since the same
50 /// request will produce the same undecodable response.
51 #[error("failed to decode response: {0}")]
52 Decode(#[from] serde_json::Error),
53}
54
55impl RazorpayError {
56 /// Whether retrying the same request could plausibly succeed.
57 ///
58 /// True for transport failures and 5xx/429 responses; false for client errors,
59 /// signature mismatches, and decode failures, which will fail identically on a
60 /// retry.
61 ///
62 /// # Retrying is not automatically safe
63 ///
64 /// This reports whether the *server* might answer differently, not whether the
65 /// call is safe to repeat. Retrying a `POST /orders` that actually succeeded
66 /// but timed out creates a **duplicate order**. Only retry non-idempotent
67 /// writes if you can deduplicate them yourself.
68 ///
69 /// # Examples
70 ///
71 /// ```
72 /// # use razorpay_api::RazorpayError;
73 /// # fn demo(err: RazorpayError) {
74 /// if err.is_retryable() {
75 /// // back off and try again
76 /// }
77 /// # }
78 /// ```
79 pub fn is_retryable(&self) -> bool {
80 match self {
81 RazorpayError::Http(e) => e.is_timeout() || e.is_connect() || e.is_request(),
82 RazorpayError::Api(e) => {
83 e.http_status.is_server_error() || e.http_status == StatusCode::TOO_MANY_REQUESTS
84 }
85 RazorpayError::UnexpectedStatus { http_status, .. } => {
86 http_status.is_server_error() || *http_status == StatusCode::TOO_MANY_REQUESTS
87 }
88 RazorpayError::InvalidUrl(_)
89 | RazorpayError::SignatureMismatch
90 | RazorpayError::Decode(_) => false,
91 }
92 }
93
94 /// The HTTP status, when the error carries one.
95 pub fn status(&self) -> Option<StatusCode> {
96 match self {
97 RazorpayError::Api(e) => Some(e.http_status),
98 RazorpayError::UnexpectedStatus { http_status, .. } => Some(*http_status),
99 RazorpayError::Http(e) => e.status(),
100 _ => None,
101 }
102 }
103
104 /// Razorpay's machine-readable error code, when this is an
105 /// [`Api`](RazorpayError::Api) error.
106 ///
107 /// # Examples
108 ///
109 /// ```
110 /// # use razorpay_api::RazorpayError;
111 /// # fn demo(err: RazorpayError) {
112 /// // Match on the code, never on the human-readable description.
113 /// if err.code() == Some("BAD_REQUEST_ERROR") {
114 /// // handle a malformed request
115 /// }
116 /// # }
117 /// ```
118 pub fn code(&self) -> Option<&str> {
119 match self {
120 RazorpayError::Api(e) => Some(&e.code),
121 _ => None,
122 }
123 }
124
125 /// The structured error body, when this is an [`Api`](RazorpayError::Api) error.
126 pub fn api_error(&self) -> Option<&ApiError> {
127 match self {
128 RazorpayError::Api(e) => Some(e),
129 _ => None,
130 }
131 }
132}
133
134/// A structured error returned by Razorpay.
135///
136/// All six documented fields are preserved: collapsing them into a single string
137/// loses `reason` and `step`, which are exactly the fields that explain *why* a
138/// payment declined.
139#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
140pub struct ApiError {
141 /// Machine-readable code, e.g. `BAD_REQUEST_ERROR`.
142 ///
143 /// Match on this rather than [`description`](Self::description), which
144 /// Razorpay may reword without notice.
145 pub code: String,
146
147 /// Human-readable message. Do not match on this text.
148 #[serde(default)]
149 pub description: String,
150
151 /// Which request field was at fault, when applicable.
152 #[serde(default)]
153 pub field: Option<String>,
154
155 /// Which side caused the failure, e.g. `business`, `customer`.
156 ///
157 /// Razorpay names this `source` on the wire; it is renamed here to avoid
158 /// colliding with [`std::error::Error::source`].
159 #[serde(default, rename = "source")]
160 pub error_source: Option<String>,
161
162 /// Which step of the flow failed, e.g. `payment_initiation`.
163 #[serde(default)]
164 pub step: Option<String>,
165
166 /// Failure reason, e.g. `input_validation_failed`.
167 #[serde(default)]
168 pub reason: Option<String>,
169
170 /// The HTTP status carried alongside the error.
171 ///
172 /// Needed for retry decisions: `code` is often the generic `BAD_REQUEST_ERROR`
173 /// for both a 400 and a 404. Defaulted because it comes from the response, not
174 /// the JSON body.
175 #[serde(default = "ok_status", skip_deserializing)]
176 pub http_status: StatusCode,
177}
178
179fn ok_status() -> StatusCode {
180 StatusCode::OK
181}
182
183/// Razorpay's error envelope: `{"error": {"code", "description", ...}}`.
184#[derive(Debug, Deserialize)]
185pub(crate) struct ApiErrorEnvelope {
186 pub error: ApiError,
187}
188
189impl ApiErrorEnvelope {
190 pub(crate) fn into_error(self, http_status: StatusCode) -> RazorpayError {
191 let mut error = self.error;
192 error.http_status = http_status;
193 RazorpayError::Api(Box::new(error))
194 }
195}