将 Result<_, error> 转换为 Result<_, MyError>,并在 Rust 中出现此错误

问题描述 投票:0回答:1

我想实现一个自定义枚举来包装多个错误,如下面的代码。

我知道我可以让它与

map_err
一起工作,但它似乎并不整洁。由于当前板条箱中未定义
Result
,因此我无法实现其转换。

遇到这种情况你会如何处理?

wrapped_fn
,好像实现了
Result<_, io::Error>
转换。你能告诉我为什么这能起作用吗?

use anyhow::Result;
use std::io;
use thiserror::Error;

#[derive(Debug, Error)]
enum MyError {
    #[error("CustomError {0}")]
    CustomError(#[from] io::Error),
}

struct MyStruct {}

fn error_fn() -> Result<(), io::Error> {
    return Err(io::Error::new(io::ErrorKind::Other, "other"));
}

fn wrapped_fn() -> Result<(), MyError> {
    error_fn()?;  // no idea why this works because it seems like implement `Result` conversion.
    Ok(())
}


fn main() {
    let result: Result<(), MyError> = error_fn().into(); // I want to make this work.
    // let result: Result<(), MyError> = error_fn().map_err(MyError::from); // This works.
}

// This cannot be implemented as well.
// impl<T> std::convert::From<Result<T, io::Error>> for Result<T, MyError>{
//     fn from(result: io::Error) -> Self{
//         result.map_err(MyError::from)
//     }
// }

错误输出

error[E0277]: the trait bound `Result<(), MyError>: From<Result<(), std::io::Error>>` is not satisfied
  --> src/main.rs:19:50
   |
19 |     let result: Result<(), MyError> = error_fn().into();
   |                                                  ^^^^ the trait `From<Result<(), std::io::Error>>` is not implemented for `Result<(), MyError>`
   |
   = note: required for `Result<(), std::io::Error>` to implement `Into<Result<(), MyError>>`
rust error-handling thiserror
1个回答
0
投票

wrapped_fn
是您通常想要做的!
?
实际上正在将现有错误
Into
转换为所需的错误类型,然后在出现错误时返回它。

如果你真的想像

main
中那样进行转换而不返回错误,那么我认为编写它的好方法确实是:

fn main() {
    let result = error_fn().map_err(MyError::from);
}
© www.soinside.com 2019 - 2024. All rights reserved.