3 ms·
rust beginner here : how do you automatically remap the error to another type using ? operator ?
by bsaul 2y ago
rust beginner here : how do you automatically remap the error to another type using ? operator ?
- tonyedgecombe 2y agoYou implement the From trait, something like this transforms an io::Error into your own type: impl From<io::Error> for MyError { fn from(_err: io::Error) -> MyError { MyError::IOError } }
- nextaccountic 2y agoThe ? operator has implicit error conversion. As another user said, it usses the From trait which performs conversions between one type and another. (Note that generally in Rust type conversions don't happen implicitly and you need to call .into() -- the ? situation is an exception) If you want to have more finer grained control on the error conversion (the From conversion is always the same for some pair of error types) you can use map_err before calling ?, like something.map_err(|e| othererror)? https://doc.rust-lang.org/std/result/enum.Result.html#method.map_err https://doc.rust-lang.org/std/result/enum.Result.html#method... If you are using anyhow and wants to attach a string message to the error (maybe to explain what happened to the user), you can also use .context(), also called .wrap_err() in eyre (eyre is a fork of anyhow) https://docs.rs/anyhow/latest/anyhow/trait.Context.html https://docs.rs/anyhow/latest/anyhow/trait.Context.html https://docs.rs/eyre/latest/eyre/trait.WrapErr.html https://docs.rs/eyre/latest/eyre/trait.WrapErr.html The following article is ten years old, but was continually updated to keep it fresh and I think it does a good job explaining how error handling works in Rust: https://burntsushi.net/rust-error-handling/ https://burntsushi.net/rust-error-handling/