3 ms·
By the way, about Rust error handling. I like the concept that any error is being returned as a function result, but there's is a huge practical problem I don't
by krick 11y ago
By the way, about Rust error handling. I like the concept that any error is being returned as a function result, but there's is a huge practical problem I don't understand how to solve with this approach. Exceptions (kind of) solve it automatically.
What if the information that "computation failed" is not enough? Say, I wrote a `getItem(User) -> itemId` function, which does a lot of calls and can fail for multiple reasons. Later I will have to admit that my API is not perfect: user isn't quite ok with the fact that operation failed, he wants to know why it failed: maybe there's no items to get at the time, maybe he isn't permitted to get them, maybe that permission is computed in real-time based on how many clicks he made today or anything else. What do I do now?
If getItem was throwing exceptions, I can fix it right away. It's not my favorite solution of that problem, but it works: I catch all exceptions separately at the caller and do something. I can provide user-friendly message as the text, that the exception will carry.
But if I was using something like Maybe monad for the error mechanism, I'm pretty much fucked. Now I have to go through huge getItem function and refactor it using some custom container-type as a return value, which will carry the reason the call failed, as well as the data itself.
From what I understood, Rust's error handling is exactly such Maybe monad with a different name. Is there built-in, idiomatic way to solve that problem?
- dbaupp 11y agoThe `Option` type (what Rust calls Maybe) is rarely used for error handling. As the article describes, Result is normally used, which allows attaching arbitrary data to the error case: http://doc.rust-lang.org/std/result/ http://doc.rust-lang.org/std/result/ For example, the io library generally returns http://doc.rust-lang.org/std/io/struct.Error.html http://doc.rust-lang.org/std/io/struct.Error.html as the information when errors occur, which includes all sorts of possibilities for what went wrong: http://doc.rust-lang.org/std/io/enum.ErrorKind.html http://doc.rust-lang.org/std/io/enum.ErrorKind.html
- e12e 11y agoIn addition to what dbaupp mentions, you might want to look at: http://blog.burntsushi.net/rust-error-handling/ http://blog.burntsushi.net/rust-error-handling/ (which was posted to hn a while back)