error-chain
error-chain copied to clipboard
Better way to compare error kinds in tests?
I'm using error-chain in some code:
#[recursion_limit = "1024"]
error_chain! {
errors {
Bundle2Decode(msg: String) {
description("bundle2 decode error")
display("{}", msg)
}
}
}
and I'm trying to verify in a test that the ErrorKind returned actually is Bundle2Decode with a particular message.
So far the best way I've found is using the assert_matches crate and
assert_matches!(err, Error(ErrorKind::Bundle2Decode(ref msg), _) if *msg == expected_msg);
That seems... suboptimal. Is there a better way to do this?
Not sure. You can always add an impl Error with a method that encapsulates the check.
I don't know your code so I'm not sure but you should use multiple error kinds or an enum as parameter instead of a string. It would be more robust.
Yeah in this case I could alternatively do that, though ultimately I would want to compare a string at some point to make sure some input I'm passing in matches the output.
Is there a way to express is-a relationships? For example, some other error kind is-a Bundle2Decode error kind. (In a language like Python you could express this with exception inheritance.) Or should I structure this in some other way?
sid0, just wondering, how would you like it look in the end, hypothetically?
sid0, just wondering, how would you like it look in the end, hypothetically?
I have roughly 3 weeks of experience writing Rust so I'm not sure I can provide an educated opinion here. But an assert_err! macro may help.
assert_err!(err, ErrorKind::Bundle2Decode(expected_msg))
or
assert_err!(err, ErrorKind::Bundle2Decode, expected_msg);
are what I'd ideally like to see.
I see what you want to do, but I'm not sure we should put it in this crate. If you use it for asserting if an error is of the right kind, what about doing the macro yourself? It's not a complicated one, that way you could learn how to do them ;)
Is there a way to express is-a relationships?
@sid0 you can write if let statements which sort of accomplish that; they give branching on matches and you don't have to extract values. Here's an example.
@TedDriggs hey -- your link 404s for me. :)
@sid0 weird - GHFM doesn't seem to support footnote annotations. Try it now.
What is so complicated about adding #[derive(PartialEq)] to the ErrorKind declaration?
Well, it prevents adding variants that are not PartialEq.
@lgarczyn at minimum, it needs to be opt-in to avoid rampant breaking changes. Also, you'd need to consider crates which opt in trying to add links or foreign links to error types that don't have that impl
Ay got it. Although it's still pretty annoying to have to use matches everywhere.