Skip to content

Commit 4b50f6d

Browse files
authored
refactor: refine error downcast related API (#1061)
1 parent 9878597 commit 4b50f6d

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

foyer/src/hybrid/error.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -28,20 +28,23 @@ pub enum Error {
2828

2929
impl Error {
3030
/// Create customized error.
31-
pub fn other<E: std::error::Error + Send + Sync + 'static>(err: E) -> Self {
32-
Self::Other(Box::new(err))
31+
pub fn other<E>(e: E) -> Self
32+
where
33+
E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
34+
{
35+
Self::Other(e.into())
3336
}
3437

3538
/// Downcast error to a specific type.
3639
///
3740
/// Only `Other` variant can be downcasted.
3841
/// If the error is not `Other`, it will return an error indicating that downcasting is not possible.
39-
pub fn downcast<T>(self) -> std::result::Result<Box<T>, Self>
42+
pub fn downcast<T>(self) -> std::result::Result<T, Self>
4043
where
4144
T: std::error::Error + 'static,
4245
{
4346
match self {
44-
Self::Other(e) => e.downcast::<T>().map_err(|e| {
47+
Self::Other(e) => e.downcast::<T>().map(|e| *e).map_err(|e| {
4548
let e: Box<dyn std::error::Error + Send + Sync + 'static> =
4649
format!("cannot downcast error: {e}").into();
4750
Self::Other(e)
@@ -92,9 +95,6 @@ mod tests {
9295
"Error or not error, that is a question.".to_string(),
9396
)));
9497
let res = e.downcast::<TestError>().unwrap();
95-
assert_eq!(
96-
res,
97-
Box::new(TestError("Error or not error, that is a question.".to_string(),))
98-
);
98+
assert_eq!(res, TestError("Error or not error, that is a question.".to_string()));
9999
}
100100
}

0 commit comments

Comments
 (0)