Skip to content

Instantly share code, notes, and snippets.

@mkatychev
Last active November 30, 2022 18:00
Show Gist options
  • Save mkatychev/9791f77128b509e7a77e794b45de6ac0 to your computer and use it in GitHub Desktop.
Save mkatychev/9791f77128b509e7a77e794b45de6ac0 to your computer and use it in GitHub Desktop.
#[macro_export]
macro_rules! from_report {
(impl From<$from:path as $context:path> for $for:ident::$variant:ident) => {
impl From<$from> for $for {
fn from(e: $from) -> Self {
Self::$variant(error_stack::Report::new(e).change_context($context))
}
}
};
(impl From<$from:path> for $for:ident::$variant:ident) => {
impl From<error_stack::Report<$from>> for $for {
fn from(e: error_stack::Report<$from>) -> Self {
Self::$variant(e)
}
}
impl From<$from> for $for {
fn from(e: $from) -> Self {
Self::$variant(error_stack::Report::new(e))
}
}
};
}
#[derive(Debug, thiserror::Error)]
#[error("network error")]
pub struct NetworkError;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("")] // NOTE this doesn't do anything
// error_stack::Report doesn't currently satisfy std::error:Error
// so an explicit impl is needed
// Anyhow(#[from] Report<anyhow::Error>),
Anyhow(Report<anyhow::Error>),
#[error(transparent)]
Io(#[from] std::io::Error),
#[error("")] // NOTE this doesn't do anything
NetworkError(Report<NetworkError>),
}
from_report!(impl From<NetworkError> for Error::NetworkError);
from_report!(impl From<NetworkError> for Error::NetworkError);
from_report!(impl From<tokio::sync::mpsc::error::SendError<Packet> as NetworkError> for Error::NetworkError);
from_report!(impl From<tonic::transport::Error as NetworkError> for Error::NetworkError);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment