error-handling - rust Snafu crate : no method named `fail` found for enum `Error` in the current scope

标签 error-handling rust

我正在尝试使用Snafu条板箱进行一些基本的错误处理。在这种情况下,我尝试在给Error而不是check_value()的情况下返回CustomInputValue::CiFloat。根据我在docs的this页面上的示例中看到的内容,我认为这会起作用:

use snafu::{Backtrace, ResultExt, Snafu, ensure};

#[derive(Debug, Snafu)]
pub enum Error{
    #[snafu(display("Incorrect Type: {:?}"), kind)]
    IncorrectInputType{kind: CustomInputValue},
}

#[derive(Debug, Clone, PartialEq)]
pub enum CustomInputValue{
    CiBool(bool),
    CiInt(i32),
    CiFloat(f64),
}

type Result<T, E = Error> = std::result::Result<T, E>;

fn main(){
    check_value(CustomInputValue::CiFloat(10.0));
}

fn check_value(val: CustomInputValue )->Result<()>{
    match val {
         CustomInputValue::CiFloat(inp)=>inp,
         _=>Error::IncorrectInputType{kind: val}.fail()?
    };
    Ok(())
}
但是,这会产生错误:
error[E0599]: no method named `fail` found for enum `Error` in the current scope
  --> src/main.rs:24:57
   |
4  | pub enum Error{
   | -------------- method `fail` not found for this
...
24 |                 _=>Error::IncorrectInputType{kind: val}.fail()?
   |                                                         ^^^^ method not found in `Error`
是什么导致此错误?我需要实现故障功能吗?我在文档中的任何地方都看不到为fail()编写的自定义Error函数,并且在文档中找不到需要fail()Error函数的任何东西。

最佳答案

#[derive(Snafu)]属性为每个枚举变量创建“上下文选择器”。这意味着Error::IncorrectInputType引用了该变体,而IncorrectInputType是具有fail()方法的生成的结构。
解决方法是使用此选择器而不是枚举:

match val {
     CustomInputValue::CiFloat(inp) => inp,
     _ => IncorrectInputType { kind: val }.fail()?
       // ^^^^^^^^^^^^^^^^^^ no Error::
};
您可以浏览SNAFU user's guide的其余部分以了解有关宏的更多信息。

另外,kind属性中的#[snafu(display(...))]放错了位置。它应该是显示部分中的参数:
#[snafu(display("Incorrect Type: {:?}", kind))]
IncorrectInputType { kind: CustomInputValue },

关于error-handling - rust Snafu crate : no method named `fail` found for enum `Error` in the current scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66058836/

相关文章:

rust - 生命周期和结构定义的混淆

windows-7 - 类型不匹配的VB6错误处理

ios - 将自定义数据包含到 iOS 故障转储中

model-view-controller - 使用 Action 过滤器进行MVC错误处理

PHP - 停止显示错误的完整路径

multithreading - Rayon 会避免为少量工作生成线程吗?

string - 我可以在 Rust 中将字符串转换为没有宏的枚举吗?

jquery - 从 JQuery Mobile 中删除错误消息?

reflection - 是否可以使用其中一种方法获取结构的名称?

rust - 使用 `move` 关键字的闭包如何创建 FnMut 闭包?