use reqwest::StatusCode;
use serde::Deserialize;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum RazorpayError {
#[error("http error: {0}")]
Http(#[from] reqwest::Error),
#[error("api error [{code}]: {description}", code = .0.code, description = .0.description)]
Api(Box<ApiError>),
#[error("unexpected http status {http_status}: {body}")]
UnexpectedStatus {
http_status: StatusCode,
body: String,
},
#[error("invalid url: {0}")]
InvalidUrl(String),
#[error("signature verification failed")]
SignatureMismatch,
#[error("failed to decode response: {0}")]
Decode(#[from] serde_json::Error),
}
impl RazorpayError {
pub fn is_retryable(&self) -> bool {
match self {
RazorpayError::Http(e) => e.is_timeout() || e.is_connect() || e.is_request(),
RazorpayError::Api(e) => {
e.http_status.is_server_error() || e.http_status == StatusCode::TOO_MANY_REQUESTS
}
RazorpayError::UnexpectedStatus { http_status, .. } => {
http_status.is_server_error() || *http_status == StatusCode::TOO_MANY_REQUESTS
}
RazorpayError::InvalidUrl(_)
| RazorpayError::SignatureMismatch
| RazorpayError::Decode(_) => false,
}
}
pub fn status(&self) -> Option<StatusCode> {
match self {
RazorpayError::Api(e) => Some(e.http_status),
RazorpayError::UnexpectedStatus { http_status, .. } => Some(*http_status),
RazorpayError::Http(e) => e.status(),
_ => None,
}
}
pub fn code(&self) -> Option<&str> {
match self {
RazorpayError::Api(e) => Some(&e.code),
_ => None,
}
}
pub fn api_error(&self) -> Option<&ApiError> {
match self {
RazorpayError::Api(e) => Some(e),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct ApiError {
pub code: String,
#[serde(default)]
pub description: String,
#[serde(default)]
pub field: Option<String>,
#[serde(default, rename = "source")]
pub error_source: Option<String>,
#[serde(default)]
pub step: Option<String>,
#[serde(default)]
pub reason: Option<String>,
#[serde(default = "ok_status", skip_deserializing)]
pub http_status: StatusCode,
}
fn ok_status() -> StatusCode {
StatusCode::OK
}
#[derive(Debug, Deserialize)]
pub(crate) struct ApiErrorEnvelope {
pub error: ApiError,
}
impl ApiErrorEnvelope {
pub(crate) fn into_error(self, http_status: StatusCode) -> RazorpayError {
let mut error = self.error;
error.http_status = http_status;
RazorpayError::Api(Box::new(error))
}
}