#Removing repetition with anyhow and error handling

5 messages · Page 1 of 1 (latest)

hollow mist
#

I have this function to write to a std::net::TcpStream and flush. The repetition to convert everything to an anyhow::Error is bugging me. I'm also not sure the "?" is the idiomatic way to return immediately in the case of error. There may be additional failing statements added in the future, too. Any suggestions for making this cleaner?

fn write(&mut self, resp: Response) -> Result<()> {
    self.socket
        .write_all(resp.encode().as_bytes())
        .map_err(anyhow::Error::from)
        .context("failed to write to socket")?;
    self.socket
        .flush()
        .map_err(anyhow::Error::from)
        .context("failed to flush socket")
}
cursive cove
#

Though you'll need to use anyhow::Context to do so

#

It's an extension trait that makes the method available to Result<T, E> where E is something you could pass to Error::from

#

(that is, std::error::Error + Send + Sync + 'static)