use std::{error::Error as StdError, fmt, iter};
pub type BoxError = Box<dyn StdError + Send + Sync + 'static>;
#[non_exhaustive]
pub enum Error {
Config(String),
InvalidRecord(String),
Closed(String),
Timeout(String),
Failed {
message: String,
source: Option<BoxError>,
},
Subscription {
name: String,
source: BoxError,
},
}
impl Error {
pub(crate) fn config(message: impl Into<String>) -> Self {
Self::Config(message.into())
}
pub(crate) fn invalid_record(message: impl Into<String>) -> Self {
Self::InvalidRecord(message.into())
}
pub(crate) fn closed(message: impl Into<String>) -> Self {
Self::Closed(message.into())
}
pub(crate) fn timeout(message: impl Into<String>) -> Self {
Self::Timeout(message.into())
}
pub(crate) fn msg(message: impl Into<String>) -> Self {
Self::Failed {
message: message.into(),
source: None,
}
}
pub(crate) fn wrap(message: impl Into<String>, source: impl Into<BoxError>) -> Self {
Self::Failed {
message: message.into(),
source: Some(source.into()),
}
}
pub(crate) fn unbox(error: BoxError, message: impl Into<String>) -> Self {
match error.downcast::<Self>() {
Ok(error) => *error,
Err(error) => Self::wrap(message, error),
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Config(message) => write!(f, "invalid configuration: {message}")?,
Self::InvalidRecord(message)
| Self::Closed(message)
| Self::Timeout(message)
| Self::Failed { message, .. } => f.write_str(message)?,
Self::Subscription { name, .. } => write!(f, "subscription {name:?} failed")?,
}
if f.alternate() {
let mut source = self.source();
while let Some(cause) = source {
write!(f, ": {cause}")?;
source = cause.source();
}
}
Ok(())
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self}")?;
let mut source = self.source();
if source.is_some() {
f.write_str("\n\nCaused by:")?;
}
while let Some(cause) = source {
write!(f, "\n {cause}")?;
source = cause.source();
}
Ok(())
}
}
impl StdError for Error {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
match self {
Self::Failed {
source: Some(source),
..
} => Some(source.as_ref()),
Self::Subscription { source, .. } => Some(source.as_ref()),
_ => None,
}
}
}
pub(crate) trait Context<T> {
fn context(self, message: impl Into<String>) -> Result<T, Error>;
#[cfg_attr(
not(any(feature = "http", feature = "health", feature = "rabbitmq")),
allow(dead_code)
)]
fn with_context<M: Into<String>>(self, message: impl FnOnce() -> M) -> Result<T, Error>;
}
impl<T, E: Into<BoxError>> Context<T> for Result<T, E> {
fn context(self, message: impl Into<String>) -> Result<T, Error> {
self.map_err(|error| Error::wrap(message, error))
}
fn with_context<M: Into<String>>(self, message: impl FnOnce() -> M) -> Result<T, Error> {
self.map_err(|error| Error::wrap(message(), error))
}
}
impl<T> Context<T> for Option<T> {
fn context(self, message: impl Into<String>) -> Result<T, Error> {
self.ok_or_else(|| Error::msg(message))
}
fn with_context<M: Into<String>>(self, message: impl FnOnce() -> M) -> Result<T, Error> {
self.ok_or_else(|| Error::msg(message()))
}
}
pub(crate) trait BoxContext {
fn context(self, message: impl Into<String>) -> BoxError;
}
impl BoxContext for BoxError {
fn context(self, message: impl Into<String>) -> BoxError {
Box::new(Error::wrap(message, self))
}
}
pub(crate) fn causes<'a>(
error: &'a (dyn StdError + 'static),
) -> impl Iterator<Item = &'a (dyn StdError + 'static)> {
iter::successors(Some(error), |&error| error.source())
}
pub(crate) fn chain(error: &(dyn StdError + 'static)) -> String {
causes(error)
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(": ")
}
macro_rules! ensure {
($cond:expr, $make:path, $($arg:tt)+) => {
if !$cond {
return Err($make(format!($($arg)+)).into());
}
};
}
pub(crate) use ensure;
#[cfg(test)]
mod tests {
use super::*;
use std::io;
#[test]
fn alternate_display_and_debug_include_every_cause() {
let error = Error::Subscription {
name: "orders".into(),
source: Box::new(Error::wrap(
"publish retry exhausted",
io::Error::other("connection reset"),
)),
};
assert_eq!(error.to_string(), r#"subscription "orders" failed"#);
assert_eq!(
format!("{error:#}"),
r#"subscription "orders" failed: publish retry exhausted: connection reset"#
);
assert_eq!(
format!("{error:?}"),
"subscription \"orders\" failed\n\nCaused by:\n publish retry exhausted\n connection reset"
);
assert_eq!(chain(&error), format!("{error:#}"));
}
}