重用“thiserror”定义中的错误消息

Rom*_*kyi 3 rust thiserror

我使用这个错误箱在我的项目中进行错误处理。

我声明一个这样的错误

#[derive(Debug, thiserror::Error)]
enum CustomErrors {
    #[error("This is custom error one")]
    CustomErrorOne,

    #[error("This is custom error two")]
    CustomErrorTwo
}
Run Code Online (Sandbox Code Playgroud)

我像这样使用这个自定义错误

// cut

match foo() {
  Err(errors) -> match errors {
     CustomErrors::CustomErrorOne => ..., // I want to get access to "This is custom error one" error message here
     CustomErrors::CustomErrorTwo => ..., // ...and here
  }
}

//cut
Run Code Online (Sandbox Code Playgroud)

我是否正确理解,由于哲学的原因,这是不可能的thiserror?并且需要创建新的错误消息?

此错误故意不出现在您的公共 API 中。(c)文件

kmd*_*eko 7

来自文档

如果您在结构体或枚举的每个变体上Display提供消息,则会为您的错误生成一个impl...#[error("...")]

因此,如果您想从 中获取该字符串CustomErrors,只需调用.to_string().

  • @RomanMahotskyi 不确定你在做什么,因为该代码可以工作,尽管它可以更简单。[参见这个游乐场示例](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=fab21afe8414be0202847cbf5c8900e3)。 (3认同)