8 ms·
Things I Enjoy in Rust: Error Handling
- wyldfire 8y agoOne of the more interesting semi-recent additions to stable rust is the question mark operator. It's not covered in this Rust Error Handling article, but it's got some of the early-exit appeal of exceptions without too much unwind magic. Unfortunately I haven't been able to get the question mark operator to work yet with my code, but it looks appealing. It's not 100% obvious to me what qualities my Result type needs in order to be able to make it work. Or whether it's bound in practice to the Result type(s) defined in std. I'm sure those details are all in the docs somewhere but I spent the time to look yet.
- CUViper 8y agoOne thing you may be missing is that the `Result::Err` in your return type must implement `From` for the `Result::Err` type where you're using the `?` operator. That's already covered if those `Err` types are identical (`From<T> for T`), otherwise you need to implement the conversion. impl From<QuestionError> for ReturnError { fn from(error: QuestionError) -> ReturnError { // TODO unimplemented!() } }
- wyldfire 8y agoOh yeah, that's likely it. Thanks! It it safe to just put a noop in there? What's From-ness? Is QuestionError defined in std? Where do I read more? EDIT: oh I see, I didn't read carefully. I just need to provide a conversion. Your example is very clear.
- ds206 8y agoIt's how you explicitly cast from one type to another. To use the ? operator with a custom error type, it needs to be converted to the std error type.
- steveklabnik 8y agoIt needs to be converted to whatever error type the function returns. That can be anything.
- Falell 8y agoThe ? operator is tied to std::ops::Try, and std::convert::From. https://doc.rust-lang.org/std/ops/trait.Try.html https://doc.rust-lang.org/std/ops/trait.Try.html https://doc.rust-lang.org/std/convert/trait.From.html https://doc.rust-lang.org/std/convert/trait.From.html
- wyldfire 8y agoOh, hey, this was great (the link to the 'From' trait). "enum CliError" -- this example was crystal clear and answered a lot of my questions.
- ChrisSD 8y agoIt's worth reading through the doc page. It's not not too long: https://doc.rust-lang.org/stable/book/ch09-02-recoverable-errors-with-result.html https://doc.rust-lang.org/stable/book/ch09-02-recoverable-er...
- wyldfire 8y agoI had read that doc page but IMO it's not very clear about how you should use Result types. It's great for showing how you might want to use the question mark with libstd but IMO less clear about writing your own functions and Result<> types (though apparently the most interesting constraint seems to be regarding your Result's E type). Someone elsewhere in this thread linked to an example of `impl From<io::Error>` and IMO that's a clear, explicit example of how to do it.
- rabito 8y agoAlso, if you use Box<Error> or failure[1]'s Error type you can get around implementing most of the conversion Traits, but you lose the ability to tell which errors can happen by just looking at the type signature and doing exhaustive matching on them. [1]: https://github.com/withoutboats/failure https://github.com/withoutboats/failure
- csomar 8y agoIf you can post your code, we can help you out. One requirement, is that your function returns a Result<Ok, Err>. The Err needs to implement the same type for all the type returned. This means you can use the "?" operator for functions that you did not create (libraries) but you'll also have to convert their Error type to your Error type.
- bfrydl 8y agoWhile I too love Rust's error handling, this explanation of it seems incomplete without discussing the ? operator and its interaction with the From trait. The convenience methods on Result itself are nice of course but they aren't really the main mechanism of error handling in my opinion.
- uzername 8y agoI've shown Rust's Result type to folks on occasion because I like it so much. The other aspect I like is the `?` operator, which allows for easier error propagation. https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator https://doc.rust-lang.org/book/ch09-02-recoverable-errors-wi...
- 59nadir 8y agoI think propagating null operators, `?`, etc., all become a bit less interesting when you consider that mostly they're just specific implementations of a monadic interface and they could all just be represented like that instead. It doesn't seem sensible to me to try to "fake" monads everywhere and add different operators for different ones when we could just have one interface that describes short-circuiting based on the data type.
- Rusky 8y agoIt's just not that simple: https://twitter.com/withoutboats/status/1027702531361857536?s=19 https://twitter.com/withoutboats/status/1027702531361857536?... Rust doesn't have higher kinded types, every closure has a unique type that implements up to three different traits, and it has imperative control flow structures that don't exist in Haskell, et al. By the time you've solved all these problems, you've moved away from monads to full-blown delimited continuations, one small step away from an effect system. And nobody really knows how to make that work while still providing Rust/C++-like "zero cost abstraction." It might be nice, but it's not at all clear that it would even be "just one interface" anyway.
- 59nadir 8y agoI'm not really talking about what's interesting or cool given a comparatively bad starting position, I'm talking about these language features in their own right. The idea of making special-case operators for what are just monads becomes less interesting in general, regardless where you started. It's certainly neat and practically useful, but it's a symptom more than it's a long-term solution. This wasn't directed at Rust in particular; many languages have these kinds of operators and even more are trying to propose them and I wonder if people just don't see the big picture and/or don't care. You can have a good and productive language without seeing the big picture or maybe realizing too late, but it's not a paragon of good design. It's definitely a design smell to introduce special-cased operators for these things. With that said, I really like Rust and I think it's an excellent language. This particular thing irks me because a lot of the people who'd exalt this kind of feature usually simultaneously argue that monads are somehow not relevant, while not realizing it's contradictory.
- icxa 8y agoI am a full time Go developer learning rust on the side for more low level things, and one of my side projects is writing an OS. Rust's error handling really feels the exact same way to Go's in my opinion, the only difference is, so far in my admittedly newcomer viewpoint, using unwrap to get to the error value, or returning an error value and doing an if err != nil check. This isn't to say anything other than agreement that I indeed like this style. I like to handle my errors as values and program around them. The thing I don't get is why all the bikeshedding and hate around "if err != nil" spam I seem to have seen here often and on other blogs. Go seems to get this "criticism" (I don't really believe it is a valid critique, for what it is worth) heaped onto it plentifully, while Rust seems generally immune to it, otherwise praised for the approach -- but it is the same approach! In fact you even have a builtin panic func in go! Can someone tell me what I may be missing?
- andrewjf 8y agoThe best parts of rust's error handling are the try!() macro (aka `?`), as well as From/Into error types allow the compiler to wrap types or convert between error types. This eliminates almost all of the go boilerplate `if err != nil` and you only handle the error where you actually need to with pattern matching and destructuring, instead. It is much nicer. Go's error handling is pretty primitive, in my opinion.
- deleted 8y ago[deleted]
- aksx 8y ago>The best parts of rust's error handling are the try!() macro (aka `?`), Go's way of providing try!() macro is less magical but almost as useful.[1] > From/Into error types allow the compiler to wrap types or convert between error types error is an interface in Go which can be easily cast/checked for the underlying type. > Go's error handling is pretty primitive I wouldn't call it primitive, I would call it simple. I like the comparison i read on a blog on HN. Rust is the 'new' C++ and Go is the new C [1] https://blog.golang.org/errors-are-values https://blog.golang.org/errors-are-values
- CuriousSkeptic 8y agoTo be fair. The idiomatic C# would be: if(TrySomeOperationThatMightFail(out var value)) { } But even with that I often wish it was more like the Rust example
- snypox 8y agoExcept 99% of methods are async in a web app where the out variable does not work.
- gamma3 8y agoReally nice! The Result reminds me of Validation from Scala. In Scala you return a Validation that is either a value or an error, and can pattern match on it. Also: trySomething().orElse("Default value")
- dep_b 8y agoI'm kind of contemplating a career switch since in mobile JavaScript cross-platform seems to become pretty big and I just don't feel very warmly about becoming a JavaScript specialist. What are the possibilities for somebody that's pretty heavy iOS senior to transfer to a role building applications or services in Rust (or Elixir, for that matter)?
- rhinoceraptor 8y agoAFAICT, 99% of the Rust jobs out there are just crypto startups. So at this point, not that great.
- dubbel 8y agoWe are an information security company in Europe using Rust for performance-critical parts of our Backend. Of course, that's just one anecdotal example, but I'd encourage you, dep_b, to look for openings. I'd guess that only very few companies use Rust exclusively right now, because of its relatively young age and because it frankly doesn't make sense everywhere, but many use another main language plus Rust.
- gameswithgo 8y agoThere is a company in Texas doing power grid /energy analysis with Rust. A company in Denmark doing non crypto stuff that I interviewed with a while back. Microsoft is using it a little, Cloudfare is using it a little.
- sanderjd 8y agoCan you disclose what the energy company in Texas is?
- agildehaus 8y agoAny job is a Rust job if you're in charge of deciding the language.
- deleted 8y ago
- XCSme 8y agoNot being familiar with Rust, the article was interesting, but I felt like it lacked examples. The Result<T, E> is also available in other languages, even in TypeScript you could have `function x(): number | Error {}`, it is just a consequence of being able to return a union of data types, why is Rust's case special? (apart from being able to handle it nicer with "match")
- guntars 8y agoRust’s is a tagged union so you can have Result<number,number>, something you can’t have in Typescript.
- 59nadir 8y agoYou can have `Result<number, number>` in both. You generally have to treat `E` as an error because of the semantics of `.map()` in every language, though, because you have to essentially ignore one of the sides. `map<Result<T, E>>` is untypable for any practical scenario where both sides matter equally. Also, just to clarify how you can have essentially the same thing you would in f.e. Haskell but in TypeScript: ``` export type Result<T, E> = Ok<T, E> | Err<T, E>; interface Ok<T, E> { type: "Ok"; unwrap(): T; map<B>(f: (x: T) => B): Result<B, E>; toMaybe(): Just<T>; or(errorValue: T): T; apply<U>(f: Result<(x: T) => U, E>): Result<U, E>; bind<U>(f: (x: T) => Result<U, E>): Result<U, E>; } interface Err<T, E> { type: "Err"; unwrap(): E; map<B>(f: (x: T) => B): Result<B, E>; toMaybe(): Nothing<T>; or(errorValue: T): T; apply<U>(f: Result<(x: T) => U, E>): Result<U, E>; bind<U>(f: (x: T) => Result<U, E>): Result<U, E>; } ```
- excepttheweasel 8y agoRight, but in Typescript you can't match on the type at compile time, you have to add a "type" field with a string tag and match on it at runtime.
- 59nadir 8y ago
- gambler 8y agoSo what do you do when you want centralized error handling, which is the whole point of try-catch idiom? >he second side effect is that it forces you to think about how to handle possible errors. Java does this with throws E and (at least in Java) it sucks and I very much prefer C#'s implicit throws. In fact, I don't think it goes far enough. If you have complex error recovery, the language should allow you to completely separate good executions paths from the bad paths. Scope guards are a step in the right direction. How would Rust code looks like if the error handling logic was something like "try X, if it fails try again, if that fails schedule another attempt via a queue, log a warning; if scheduling fails log a fatal error"? Sure, handling this stuff with try-catch looks horrible. But I've thought long an hard about how to simplify it and using tricks like .unwrap_or (which you can simulate in C# to some extent) does not cut it, because error handling often requires to operate on method-scoped variables (e.g. for logging).
- ChrisSD 8y agoDepends what exactly you're looking to do. You can propagate errors with the `?` operator. And you can match on the specific error at a higher level. The docs[0] do give a more complex example of error matching: fn main() { let f = File::open("hello.txt"); let f = match f { Ok(file) => file, Err(error) => match error.kind() { ErrorKind::NotFound => match File::create("hello.txt") { Ok(fc) => fc, Err(e) => panic!("Tried to create file but there was a problem: {:?}", e), }, other_error => panic!("There was a problem opening the file: {:?}", other_error), }, }; } Although they also provide a slightly simpler alternative for this particular case. [0] https://doc.rust-lang.org/stable/book/ch09-02-recoverable-errors-with-result.html https://doc.rust-lang.org/stable/book/ch09-02-recoverable-er...
- gambler 8y agoDoesn't look that much cleaner than try/catch, to be honest. What I would really like to see in C#: public int DoThing(int y) { //logic } catch (SomeException e) { //handle things return 0; } This would remove a lot of useless syntactic garbage without the need for any radical changes in the language. (It would translate to try-catch that wraps the entire body of the method.) But so far I gave up on syntax-level error handling of any complexity. Generally, I just write multiple "agents" and all the error handling, retries and recovery is simply done by separate agent(s). The agent that tries to perform the initial actions simply records that it failed in some persistent storage and terminates or goes on to do something else.
- CountHackulus 8y agoThis is an extremely common pattern in Erlang and is super useful so it's nice to see Rust embrace it.
- zmmmmm 8y agoIt's interesting to see modern languages tackling checked error handling. Particularly in the light that Java's checked exceptions are widely considered to have been a failure. Yet I wonder if Java had better support for things like union types etc. if it would have turned out differently. After all, it did offer at least potential to achieve what everyone is after: you can write a piece of code and know for sure that you handled every possible type of error. The most painful aspect of Java's (original) exceptions was how the only mechanism to handle multiple errors as a single case was using inheritance in the exception hierarchy. The result was that they propagated through interfaces and broke downstream code and it became pretty much impossible to design and maintain a stable API without wrapping exceptions excessively which in turn destroys the utility of the exception hierarchy, making the whole exercise futile. The article seems a little superficial though. Immediately exiting with 'panic' does not seem like a real error handling approach for any realistic application. It doesn't show how you could handle different types of errors (eg: file not found vs I/O error reading file) with different cases. The case it does present is easily handled elegantly by nearly any error handling design.
- int_19h 8y agoI think the biggest problem with Java exception specs is that they're not composable. In other words, I can't define a method X that calls another method Y - potentially via dynamic dispatch - and has an exception specification of "whatever Y throws, plus E". This manifests almost immediately. For example, suppose you wanted to implement a key/value database with disk storage. The logical core interface for it would be java.util.Map, except for the fact that its methods are declared as non-throwing; thus, you cannot propagate IOException from the underlying storage layer, unless you wrap it into unchecked RuntimeException. Conversely, java.lang.Appendable is a very generic interface for appending characters or sequences of characters to something. But because its designers knew that some of its implementations would be backed by I/O, all mutating methods in that interface are declared as throwing IOException. Thus, any generic code that tries to work with Appendable has to always assue that it can throw, and has to declare itself as throwing the same exception to propagate. And now the user of that generic code passes a no-throw implementation of Appendable to it, but still has to "handle" IOException that they know will never actually happen. Or come up with some convoluted scheme, like java.util.Formatter does. This one wraps Appendable, but swallows all I/O exceptions to avoid having to propagate them in the most common case, where the wrapped Appendable is a StringBuilder. But since there are other possibilities, it still has to expose some API to examine such exceptions, which it does by providing a method on Formatter that returns the last swallowed exception that was thrown by Appendable. Of course, now you have to remember to actually check it, and you will silently get an incorrect result if you do not, which is worse than unchecked exceptions in the same scenario. This all gets especially bad one you start working with HOFs, because their contracts are largely defined in terms of the behavior of functions that are passed to them. The old Java lambda proposal by Neal Gafter noted this, and proposed extending the syntax for generics to cover exception specifications (via union typing, indeed). In the end, they added UncheckedIOException to the standard library, specifically so that stuff like Stream.map() can be implemented on top of files, and propagate exceptions, without declaring them.
- csomar 8y agoI don't particularly like the solution presented. 1. The Rust community is biased against the usage of "unwrap". It was supposed to make prototyping easier. It should not have been there and should not be used. The correct way will be to "evaluate" the function and either return a result or "propagate" the error to some part of your application that will handle "all" the errors. Whether they are your code errors, or errors thrown by other libraries. 2. The code will look even more succinct with the "?" operator: > let value = some_operation_that_might_fail()?; 3. If the function fail, the program should handle the failure. By design, a failure should not result on setting a "default value". That's not an error but more like an "option". The correct type the guy should have used is the Option type. Or more like an option inside a result. The option could return a value or not. If not, you set a default value.
- epage 8y ago> 1. The Rust community is biased against the usage of "unwrap". It was supposed to make prototyping easier. It should not have been there and should not be used. I'm a little confused on this point you are making. You say the Rust community is biased against `unwrap` which makes it sound like you think that is wrong but then you proceed to say it shouldn't be there, making it sound like you agree. `unwrap` has legitimate uses in product code as an assertion. Normally I recommend `expect` instead so that the assertion is self-documenting but there are times where the the scope of the assumption you are making is so small, it is obvious and doesn't need a comment, for example if I partition a collection based on the result [0] [0]: https://doc.rust-lang.org/stable/rust-by-example/error/iter_result.html#collect-all-valid-values-and-failures-with-partition https://doc.rust-lang.org/stable/rust-by-example/error/iter_... > . If the function fail, the program should handle the failure. By design, a failure should not result on setting a "default value". That's not an error but more like an "option". From the function's perspective, it errored, but from your perspective, it failed and you want to fallback to a default value. Yes, someone could express this instead as an `Option` or a `Result<Option, _>` - Sometimes you just don't need that extra boiler plate - Sometimes you want to provide context for why something failed in case the user considers it an error as well. You can't express that with `Option`.
- 8y ago
- miohtama 8y agoThe article is a good opinion, but lacks necessary wider discussion in the context of all programming. 1) Is Rust error handling somehow better than in a programming language X? 2) Is it because of Rust or because standard libraries or something else (developer laziness, writing silent exception eating) 3) Why other programming languages choose to do it other ways? Now the article reads like Rust education, which is good, but other commenters here find it very subjective.
- namelosw 8y agoDesigns like Java which have NullPointerException simply ignore null. Modeling T instead of T | null is just too convenient. It's a lazy design. I'm fine with most of those new ways of error handling, although some feel better and the others feel a little bit awkward. If some concept exists (exception/emptiness/async), model it, handle it. Instead of just ignore it and leak the responsibility to the users.
- BooneJS 8y agoTensorFlow has a StatusOr C++ class that allows functions to return a value that can be first checked to be result.ok() (no error), and then the actual value can be unwrapped. It’s Google’s way of not using exceptions. https://github.com/tensorflow/tensorflow/blob/38c762add3559b3292139c1d839c706a1695e2fc/tensorflow/stream_executor/lib/statusor.h https://github.com/tensorflow/tensorflow/blob/38c762add3559b...