The Missing Piece in Rust Error Handling

79 points by snej


abrambleninja

Wow, this is very cool, thanks so much for sharing! I've had this exact frustration with error types before and this seems like a really nice way to handle it. The ability to define errors as a small set of them that actually can occur at a given call instead of packing it into module-level enum with irrelevant errors is so nice for being able to refine what actually happens. I'm very excited to give this a go!

Another annoyance that I've run into for error handling is that it is annoying to write code that returns multiple errors. Say you're writing a backend CRUD application and you have to verify the fields of a create request. It would be nice to be able to return all fields that were in violation of the constraints rather than just the one, but it's difficult to do that with Result since ? returns early. I've seen some solutions using some sort of error vec crate, but they've never felt very elegant to me. I'm curious to see if some constructs in this crate have any hints at a solution.

goldstein

exposing ParseIntError in this way feels iffy: this isn’t a failure to parse just any int, this is a failure to parse a port in particular. suppose your address contains two ints (maybe you’re connecting to a redis db and you have a port and a db number): now ParseIntError is ambiguous. this breaks either ? or automatic widening: now you need to specify which particular int failed to parse, by doing something like .map_err(ParsePortError) manually (just #[context] won’t do if you want to change this programmatically, because #[context] doesn’t change types).

for that reason, I think impls like From<ParseIntError> for ConnectionError are anti-patterns, and generally you should try to wrap “low-level” errors like these into more semantic types (or variants, you can have ConnectionError::ParsePort(ParseIntError) and ConnectionError::ParseDb(ParseIntError)). would be nice to see some infrastructure for that, although I’m not sure if it’s doable without some heavy macro use.

(a separate question is whether you should expose underlying errors at all in any particular case: maybe redis will transition to named dbs, and you’d wish you just left that error opaque)