Reputation: 3411
I'm trying to use the Snafu crate for some basic error handling. In this case, I'm trying to return an Error
when check_value()
is given anything but a CustomInputValue::CiFloat
. Based on what I was seeing in examples on this page from the docs, I thought this would work:
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(())
}
However, this produces the error:
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`
What's causing this error? Do I need to implement a fail function? I don't see anywhere in the docs such a custom fail()
function being written for Error
, and can't find anything bout requiring a fail()
function for Error
in the docs.
Upvotes: 1
Views: 1009
Reputation: 60092
The #[derive(Snafu)]
attribute creates "context selectors" for each enum variant. That means that Error::IncorrectInputType
refers to the variant, while IncorrectInputType
is a generated struct which has the fail()
method.
The fix is to use this selector instead of the enum:
match val {
CustomInputValue::CiFloat(inp) => inp,
_ => IncorrectInputType { kind: val }.fail()?
// ^^^^^^^^^^^^^^^^^^ no Error::
};
You can browse the rest of the SNAFU user's guide to know more about the macro.
Also, the kind
in the #[snafu(display(...))]
attribute is misplaced. It should be a parameter within the display portion:
#[snafu(display("Incorrect Type: {:?}", kind))]
IncorrectInputType { kind: CustomInputValue },
Upvotes: 3