top | item 37950485

(no title)

zakm | 2 years ago

The only argument I can think of against this would be that it would maybe slightly discourage adding the verbose details and would generally decrease the quality of error messages slightly. That said, even so it's probably worth the trade.

discuss

order

bibabaloo|2 years ago

Errors are composable so this isn't such a problem in practice. Most of the prod code I wrote would do something like this

    use thiserror::Error;

    #[derive(Error, Debug)]
    enum Error {
        #[error("Could not open given decomp file: {0}")]
        FileOpen(#[from] std:io::Error),
        #[error("Compressed read error: {0}")]
        CompressedRead(#[from] gz::Error)
    }

    fn decomp(filename: &Path) -> Result<Vec<u8>, Error> {
        let fd = File::open(filename)?;  // File is automatically closed by its destructor.
        let zd = GzDecoder::new(fd);   // flate2::read::GzDecoder::new does not return an error.
        let mut data = Vec::new();     // Rust makes the caller allocate the buffer for reads.
        zd.read_to_end(&mut data)?;
        Ok(data)
    }

Mavvie|2 years ago

Huh, can you explain that a bit more for a rust noob like myself?

1. How does it know how to create your Error enum? I guess it's from the #[from]? 2. What happens if your method tries to return something that's not an io::Error or a gz::Error? I guess the compiler catches that? 3. How would you handle doing this for multiple methods in the same file? Would you rename your enum to DecompError or something to avoid conflicts?

slantedview|2 years ago

I agree, especially if you can _choose_ when you want to be a bit more verbose and add more detail, or not.