You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Currently, we have a number of crates where we have a top-level Errorenum, but our functions return anyhow::Error instead of the enum. It's been pointed out that this is not idiomatic and it would be better to just return Error and use thiserror's transparent forwarding. I'm confused about how to idiomatically handle matching on forwarded error variants. Consider the following crate structure:
high-level
/ \
low-level-a low-level-b
where high-level defines Error, low-level-a defines ErrorA and low-level-b defines ErrorB. If each of the enums includes an IoError(std::io::Error) variant, how is code supposed to match on the std::io::Error? To make the question concrete, consider this code, which is what I currently imagine:
#[derive(thiserror::Error,Debug)]enumError{#[error("something bad happened: {0}")]Bad(String),}#[derive(thiserror::Error,Debug)]enumErrorA{}#[derive(thiserror::Error,Debug)]enumErrorB{}fnf() -> anyhow::Result<()>{Err(std::io::Error::new(std::io::ErrorKind::Other,"oh no!").into())}fnmain(){let result = f();match result {Err(err) => {ifletSome(err) = err.downcast_ref::<std::io::Error>(){// Handle the io error.eprintln!("io error: {}", err);}else{eprintln!("Not an io error: {}", err);}}Ok(()) => {eprintln!("Everything is fine")}}}
That is, we downcast to std::io::Error and it doesn't matter if the std::io::Error comes from high-level, low-level-a, low-level-b, or another crate that high-level starts using later: the user of the high-level API can reliably and compactly catch std::io::Errors.
Thanks for any insights!
The text was updated successfully, but these errors were encountered:
Currently, we have a number of crates where we have a top-level
Error
enum
, but our functions returnanyhow::Error
instead of theenum
. It's been pointed out that this is not idiomatic and it would be better to just returnError
and usethiserror
's transparent forwarding. I'm confused about how to idiomatically handle matching on forwarded error variants. Consider the following crate structure:where
high-level
definesError
,low-level-a
definesErrorA
andlow-level-b
definesErrorB
. If each of theenum
s includes anIoError(std::io::Error)
variant, how is code supposed to match on thestd::io::Error
? To make the question concrete, consider this code, which is what I currently imagine:This is how we currently do it:
That is, we downcast to
std::io::Error
and it doesn't matter if thestd::io::Error
comes fromhigh-level
,low-level-a
,low-level-b
, or another crate thathigh-level
starts using later: the user of the high-level API can reliably and compactly catchstd::io::Error
s.Thanks for any insights!
The text was updated successfully, but these errors were encountered: