logoalt Hacker News

athrowaway3zyesterday at 8:50 PM3 repliesview on HN

My controversial take on Rust errors is to use anyhow everywhere until you have an immediate demand for explicit Enums. YANGNI

The pros for using anyhow are big: Easily stack errors together - eg file.open().context(path) -, errors are easily kept up to date, and easy to find where they occur.

An enum error is pleasing when you're finished, but cumbersome in practice.

It's niche situation that you need to write a function that exposes a meaningful Error state the caller can branch on. If the return state is meaningful, you usually don't put it in the Err part. eg parsers using { Ok,Incomplete,Error }. IMO Error enums are best for encoding known external behavior like IO errors.

For example: The Sender.send_deadline returning { Timeout, Closed } is the exception in being useful. Most errors are like a Base64 error enums. Branching on the detail is useless for 99.99% of callers.

i.e. If your crate is meant for >1000 users, build the full enum.

For any other stuff, use anyhow.


Replies

zapharyesterday at 9:09 PM

If your error domain has only one useful category why not just create an error type with a useful message and be done with it. Why use anyhow at all? You are essentially saying the error domain is small so the work is tiny anyway.

anyhow seems useful in the very top layers where you basically just want bubble the useful errors modeled elsewhere to a top layer that can appropriately handle them. I don't think a crate should abdicate from modeling the error domain any more than they should abdicate from modeling the other types.

show 2 replies
phireyesterday at 9:56 PM

Yeah, I’m the same. I default to anyhow unless I need a strong API boundary (like if I’m publishing a library crate)

Sure, it’s slightly more error prone than proper enum errors, but it’s so much less friction, and much better than just doing panic (or unwrap) everywhere.

sunshowersyesterday at 9:34 PM

LLMs are pretty good at generating and maintaining error enums for you these days.