use std::fmt;
#[derive(Debug)]
pub struct Error {
pub status: u16,
pub code: String,
pub message: String,
pub request_id: Option<String>,
pub retriable: bool,
source: Option<Box<dyn std::error::Error + Send + Sync + 'static>>,
}
impl Error {
pub(crate) fn new(status: u16, code: &str, message: impl Into<String>) -> Self {
Error {
status,
code: code.to_string(),
message: message.into(),
request_id: None,
retriable: false,
source: None,
}
}
pub(crate) fn invalid(message: impl Into<String>) -> Self {
Error::new(0, "INVALID_REQUEST", format!("bitmomo: {}", message.into()))
}
#[cfg(feature = "client")]
pub(crate) fn schema(message: impl Into<String>) -> Self {
Error::new(0, "SCHEMA_ERROR", format!("bitmomo: {}", message.into()))
}
#[allow(dead_code)]
pub(crate) fn with_source(
mut self,
source: impl std::error::Error + Send + Sync + 'static,
) -> Self {
self.source = Some(Box::new(source));
self
}
pub fn from_response(status: u16, body: &str) -> Self {
let data: serde_json::Value = if body.is_empty() {
serde_json::Value::String(String::new())
} else {
serde_json::from_str(body)
.unwrap_or_else(|_| serde_json::Value::String(body.to_string()))
};
let obj = data.as_object();
let field = |name: &str| obj.and_then(|o| o.get(name));
let raw_error = field("error").and_then(|v| v.as_str()).unwrap_or("");
let mut code = if !raw_error.is_empty() && is_code(raw_error) {
raw_error.to_string()
} else {
String::new()
};
if code.is_empty() {
code = match field("code").and_then(|v| v.as_str()) {
Some(legacy) if !legacy.is_empty() => legacy.to_string(),
_ => default_code(status).to_string(),
};
}
let mut message = field("message")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
if message.is_empty() {
message = if !raw_error.is_empty() && !is_code(raw_error) {
raw_error.to_string()
} else if let Some(text) = data.as_str().filter(|s| !s.is_empty()) {
text.to_string()
} else {
format!("Request failed with status {status}")
};
}
let retriable = field("retriable")
.and_then(|v| v.as_bool())
.unwrap_or(matches!(status, 408 | 429 | 502 | 503 | 504));
let request_id = field("request_id")
.and_then(|v| v.as_str())
.map(str::to_string);
Error {
status,
code,
message,
request_id,
retriable,
source: None,
}
}
}
fn is_code(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 64
&& value
.bytes()
.all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_')
}
fn default_code(status: u16) -> &'static str {
match status {
400 => "BAD_REQUEST",
401 => "UNAUTHORIZED",
403 => "FORBIDDEN",
404 => "NOT_FOUND",
405 => "METHOD_NOT_ALLOWED",
409 => "CONFLICT",
410 => "GONE",
415 => "UNSUPPORTED_MEDIA_TYPE",
422 => "UNPROCESSABLE",
423 => "LOCKED",
429 => "RATE_LIMIT",
500 => "INTERNAL_ERROR",
501 => "NOT_IMPLEMENTED",
502 => "BAD_GATEWAY",
503 => "SERVICE_UNAVAILABLE",
504 => "GATEWAY_TIMEOUT",
_ if (400..500).contains(&status) => "CLIENT_ERROR",
_ => "SERVER_ERROR",
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"bitmomo: {} ({}): {}",
self.code, self.status, self.message
)
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source
.as_deref()
.map(|e| e as &(dyn std::error::Error + 'static))
}
}