logoalt Hacker News

masklinnlast Tuesday at 5:36 PM2 repliesview on HN

> But I fail to see how having convenience equates to ignoring the error.

The convenience of writing `?` means nobody will bother wrapping errors anymore. Is what I understand of this extremely dubious argument.

Since you could just design your `?` to encourage wrapping instead.


Replies

NobodyNadalast Tuesday at 5:53 PM

> Since you could just design your `?` to encourage wrapping instead.

Which is exactly what Rust does -- if the error returned by the function does not match the error type of `?` expression, but the error can be converted using the `From` trait, then the conversion is automatically performed. You can write out the conversion implementation manually, or derive it with a crate like thiserror:

    #[derive(Error)]
    enum MyError {
        #[error("Failed to read file")
        IoError(#[from] std::io::Error)
        // ...
    }

    fn foo() -> Result<(), MyError> {
        let data = std::fs::read("/some/file")?;
        // ...
    }
You can also use helper methods on Result (like `map_err`) for inserting explicit conversions between error types:

    fn foo() -> Result<(), MyError> {
        let data = std::fs::read("/some/file").map_err(MyError::IoError)?;
        // ...
    }
show 2 replies
sa46last Tuesday at 6:21 PM

> The convenience of writing `?` means nobody will bother wrapping errors anymore.

A thread from two days ago bemoans this point:

https://news.ycombinator.com/item?id=44149809