feat: unified error type (#308)
* feat: unified error type * fix: use type id to compare transport type
This commit is contained in:
parent
c74b26b3e3
commit
e615300fea
1 changed files with 286 additions and 161 deletions
|
|
@ -64,7 +64,7 @@
|
|||
//! }
|
||||
//! ```
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::{borrow::Cow, sync::Arc};
|
||||
|
||||
use crate::service::{RxJsonRpcMessage, ServiceRole, TxJsonRpcMessage};
|
||||
|
||||
|
|
@ -141,6 +141,9 @@ where
|
|||
R: ServiceRole,
|
||||
{
|
||||
type Error: std::error::Error + Send + Sync + 'static;
|
||||
fn name() -> Cow<'static, str> {
|
||||
std::any::type_name::<Self>().into()
|
||||
}
|
||||
/// Send a message to the transport
|
||||
///
|
||||
/// Notice that the future returned by this function should be `Send` and `'static`.
|
||||
|
|
@ -241,3 +244,36 @@ where
|
|||
std::future::ready(Ok(()))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("Transport [{transport_name}] error: {error}")]
|
||||
pub struct DynamicTransportError {
|
||||
pub transport_name: Cow<'static, str>,
|
||||
pub transport_type_id: std::any::TypeId,
|
||||
#[source]
|
||||
pub error: Box<dyn std::error::Error + Send + Sync>,
|
||||
}
|
||||
|
||||
impl DynamicTransportError {
|
||||
pub fn new<T: Transport<R> + 'static, R: ServiceRole>(e: T::Error) -> Self {
|
||||
Self {
|
||||
transport_name: T::name(),
|
||||
transport_type_id: std::any::TypeId::of::<T>(),
|
||||
error: Box::new(e),
|
||||
}
|
||||
}
|
||||
pub fn downcast<T: Transport<R> + 'static, R: ServiceRole>(self) -> Result<T::Error, Self> {
|
||||
if !self.is::<T, R>() {
|
||||
Err(self)
|
||||
} else {
|
||||
Ok(self
|
||||
.error
|
||||
.downcast::<T::Error>()
|
||||
.map(|e| *e)
|
||||
.expect("type is checked"))
|
||||
}
|
||||
}
|
||||
pub fn is<T: Transport<R> + 'static, R: ServiceRole>(&self) -> bool {
|
||||
self.error.is::<T::Error>() && self.transport_type_id == std::any::TypeId::of::<T>()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue