use std::collections::HashMap;
use std::fmt;
use serde_json::Value;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorKind {
Api,
Transport,
InvalidArgument,
Signature,
}
#[derive(Debug, Clone)]
pub struct OpensmsError {
pub kind: ErrorKind,
pub status: u16,
pub r#type: Option<String>,
pub title: Option<String>,
pub detail: Option<String>,
pub code: Option<String>,
pub trace_id: Option<String>,
pub errors: Option<HashMap<String, Vec<String>>>,
pub request_id: Option<String>,
pub retry_after: Option<u64>,
pub body: Option<Value>,
pub message: String,
}
impl OpensmsError {
fn bare(kind: ErrorKind, status: u16, message: String, code: Option<String>) -> Self {
Self {
kind,
status,
r#type: None,
title: None,
detail: None,
code,
trace_id: None,
errors: None,
request_id: None,
retry_after: None,
body: None,
message,
}
}
pub fn transport(message: impl Into<String>) -> Self {
Self::bare(ErrorKind::Transport, 0, message.into(), None)
}
pub fn invalid_argument(message: impl Into<String>) -> Self {
Self::bare(
ErrorKind::InvalidArgument,
0,
message.into(),
Some("invalid_argument".to_string()),
)
}
pub fn signature(code: &str, message: impl Into<String>) -> Self {
Self::bare(
ErrorKind::Signature,
0,
message.into(),
Some(code.to_string()),
)
}
pub(crate) fn from_response(
status: u16,
body: &[u8],
request_id: Option<String>,
retry_after: Option<u64>,
) -> Self {
let parsed: Option<Value> = if body.is_empty() {
None
} else {
serde_json::from_slice(body).ok()
};
let obj = parsed.as_ref().and_then(|v| v.as_object());
let s = |k: &str| -> Option<String> {
obj.and_then(|o| o.get(k))
.and_then(|v| v.as_str())
.map(String::from)
};
let errors = obj
.and_then(|o| o.get("errors"))
.and_then(|v| serde_json::from_value::<HashMap<String, Vec<String>>>(v.clone()).ok());
let detail = s("detail");
let title = s("title");
let message = detail
.clone()
.or_else(|| title.clone())
.unwrap_or_else(|| format!("OpenSMS request failed with status {status}"));
let (r#type, code, trace_id) = (s("type"), s("code"), s("trace_id"));
let raw = match parsed {
Some(v) => Some(v),
None if !body.is_empty() => {
Some(Value::String(String::from_utf8_lossy(body).into_owned()))
}
None => None,
};
Self {
kind: ErrorKind::Api,
status,
r#type,
title,
detail,
code,
trace_id,
errors,
request_id,
retry_after,
body: raw,
message,
}
}
}
impl fmt::Display for OpensmsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.code {
Some(code) => write!(
f,
"OpenSMS error {} ({}): {}",
self.status, code, self.message
),
None => write!(f, "OpenSMS error {}: {}", self.status, self.message),
}
}
}
impl std::error::Error for OpensmsError {}
pub type Result<T> = std::result::Result<T, OpensmsError>;