feat: add other helpers for ProviderError (#14325)

This commit is contained in:
Matthias Seitz
2025-02-08 17:27:55 +01:00
committed by GitHub
parent d56985a298
commit b2011353f2

View File

@ -145,9 +145,42 @@ pub enum ProviderError {
/// Received invalid output from configured storage implementation.
#[error("received invalid output from storage")]
InvalidStorageOutput,
/// A wrapper for arbitrary errors requiring thread-safety and cloneability.
/// Any other error type wrapped into a clonable [`AnyError`].
#[error(transparent)]
Any(#[from] AnyError),
Other(#[from] AnyError),
}
impl ProviderError {
/// Creates a new [`ProviderError::Other`] variant by wrapping the given error into an
/// [`AnyError`]
pub fn other<E>(error: E) -> Self
where
E: core::error::Error + Send + Sync + 'static,
{
Self::Other(AnyError::new(error))
}
/// Returns the arbitrary error if it is [`ProviderError::Other`]
pub fn as_other(&self) -> Option<&(dyn core::error::Error + Send + Sync + 'static)> {
match self {
Self::Other(err) => Some(err.as_error()),
_ => None,
}
}
/// Returns a reference to the [`ProviderError::Other`] value if this type is a
/// [`ProviderError::Other`] and the [`AnyError`] wraps an error of that type. Returns None
/// otherwise.
pub fn downcast_other_ref<T: core::error::Error + 'static>(&self) -> Option<&T> {
let other = self.as_other()?;
other.downcast_ref()
}
/// Returns true if the this type is a [`ProviderError::Other`] of that error
/// type. Returns false otherwise.
pub fn is_other<T: core::error::Error + 'static>(&self) -> bool {
self.as_other().map(|err| err.is::<T>()).unwrap_or(false)
}
}
impl From<alloy_rlp::Error> for ProviderError {
@ -202,3 +235,19 @@ impl From<ConsistentViewError> for ProviderError {
Self::ConsistentView(Box::new(error))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(thiserror::Error, Debug)]
#[error("E")]
struct E;
#[test]
fn other_err() {
let err = ProviderError::other(E);
assert!(err.is_other::<E>());
assert!(err.downcast_other_ref::<E>().is_some());
}
}