use std::fmt;
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Error {
pub code: String,
pub message: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub details: Option<Box<Value>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hint: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mutation_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<u16>,
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
impl Error {
pub fn new(code: impl Into<String>, message: impl Into<String>) -> Error {
Error { code: code.into(), message: message.into(), details: None, hint: None, mutation_id: None, status: None }
}
pub fn with_hint(mut self, hint: impl Into<String>) -> Error {
self.hint = Some(hint.into());
self
}
pub fn with_details(mut self, details: Value) -> Error {
self.details = Some(Box::new(details));
self
}
pub(crate) fn network(e: impl fmt::Display) -> Error {
Error::new("network", e.to_string())
}
pub(crate) fn storage(e: impl fmt::Display) -> Error {
Error::new("storage", e.to_string())
}
pub(crate) fn config(m: impl Into<String>) -> Error {
Error::new("config", m)
}
pub fn reason(&self) -> Option<&str> {
self.details.as_ref()?.get("reason")?.as_str()
}
pub fn is_transient(&self) -> bool {
matches!(self.code.as_str(), "network" | "internal" | "rate_limited" | "timeout" | "shutting_down")
|| self.status.is_some_and(|s| s >= 500 || s == 429)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.code, self.message)?;
if let Some(h) = &self.hint {
write!(f, " ({h})")?;
}
Ok(())
}
}
impl std::error::Error for Error {}
impl From<serde_json::Error> for Error {
fn from(e: serde_json::Error) -> Error {
Error::new("invalid_json", e.to_string())
}
}
#[cfg(feature = "sqlite")]
impl From<rusqlite::Error> for Error {
fn from(e: rusqlite::Error) -> Error {
Error::storage(e)
}
}