12 ms·
An Open Letter to the Go Team About Try
- tech_dreamer 7y agoI agree with blog author's sentiments. Go is a bit too imperative but that really aides in a team environment. Though the Golang's constructs are a bit bland (especially error handling) it actively prevents code to be too intelligent there by aiding readability I am able to work on the code I wrote 2 years ago with little difficulty in Golang and I can't make the same claim for other `leading` languages (though I assume full responsibility for what happened) Edit: grammer and spelling
- apsdsm 7y agoThis blog pretty well sums up my feelings about the try method. It just doesn’t really seem necessary. I’m sure it would help in some of my code, but importantly not all of my code, and if a construct is only available some of the time, I will inevitably favor the doing the same way all of the time rather than adding a little syntactic sugar every now and then. I’d much rather see some kind of genetics support get well integrated, given that’s a problem I run into fairly often.
- 100100010001 7y agoAgreed! (Though I’m assuming you meant to type generics. However, I’d love a library to alter genetics)
- apsdsm 7y agoHahah this is what I get for typing on my phone.
- ngngngng 7y agoBill helped me with my resume once in the Go slack channel. Great guy. I also happen to agree wholeheartedly that introducing try would be disastrous to the mostly consistent codebases Go is currently able to painlessly produce. Personally I don't want error handling changed at all. It's very repetitive in it's current state, but clearer than in any other language I've used.
- ben_jones 7y agoBeen using Go for ~4 years and I agree - although I would like to see more documentation about scaling error handling in production codebases however. Controversially I do support generics in go2.
- asdkhadsj 7y agoEh, I feel like Go errors are a mess, personally. Though, I'm not sure how to solve them. Mind you, this is after ~5 years of use, so it's not from "an outsider" - I hope, at least lol. Most of blame for the mess is that the error interface throws away meaningful information. Then the caller is left mentally checking how to handle the error. Do I value check? Type cast? String check? Does the library expose a function to check, or do I do it myself? Can I get stack traces in some cases without introducing a production cost? I'm not sure if Go needs a different type of error interface (ie diff methods), or if it needs Generics to solve this properly in my view. But, I just know I've hated the experience. After I switched to Rust it all felt so familiar, and yet so different. I believe Rust and Go share error patterns. Yet in Rust I'm never left wondering what an error is, what I should do with it, how I check for specific types. This is largely due to awesome enum support and of course generics. Does Go need this feature set to "fix" my complaints with errors? Probably not.. but I do think it needs something. Though I will agree, I don't think the `if err != nil` is fundamentally the problem with Go's errors, at all. Sure, the UX could be improved, but that's another story all together imo.
- hermitdev 7y agoHonest question as a non Go user: how would generics (from a C# perspective) help? I assume that Go generics would be analogous those in C#. Edit: spelling, genetics to generics.
- Nullabillity 7y agoRust has a wrapper type `Result<ReturnType, ErrorType>`[0] that essentially works the same was as Go's `return value, err` idiom, but is safer because the type is defined so that you can't access the returned value unless you also handle the error condition, and it can have a convenience syntax for chaining since it is a dedicated unambiguous type. The compiler also specifically warns you about unused `Result`s, to avoid unhandled errors, and the API is structured so that nonsensical states such as `(nil, nil)` or `(value (!= nil), error (!= nil))` are impossible (unless specifically opted into). Without generics you would have to either throw away the type information, reimplement a `Result` type for every value type, or copy/paste the implementation at each usage site (the common Go pattern). Go's support for multiple returns itself is also a hack around the lack of support for tuples (which would be trivial to implement if you had generics). [0]: https://doc.rust-lang.org/std/result/enum.Result.html https://doc.rust-lang.org/std/result/enum.Result.html
- alpb 7y agoDoes anyone have a link to the "try" proposal the author is advocating against? It's not clearly linked in the article.
- zmj 7y agoGo errors prioritize explicitness, in declaration of what functions might fail, and in handling of those failures. It seems like a mistake to add a language feature that works against explicit handling. At minimum, the endorsement of returning the raw error reduces clarity on what "good error handling code" should look like.
- marcus_holmes 7y agoagree totally. I'd prefer to see an official errors.Wrap function instead of "try", for the reasons you cite. (shout out to Dave Cheney's excellent "pkg/errors" implementation of error wrapping)
- foota 7y agoTry aka ASSIGN_OR_RETURN
- TheChaplain 7y agoThis proposal really seem to rile up the community, can't it be shelved and revised until let's say v2.4 or something?
- tgsovlerkhgsel 7y agoOf course it can. It can also be shelved indefinitely or not done, but at some point, it's time to make a decision. Opponents of this would of course prefer it to be "shelved" instead.
- munificent 7y ago> Rob Pike gave a talk last year at the Go Sydney meetup where he talked about the Go 2 changes. In his talk, he suggested that the use of if err != nil in code bases is nowhere near as common as the vocal minority suggest. This page shows the most common words found in a large corpus of open source Go code on GitHub: https://anvaka.github.io/common-words/#?lang=go https://anvaka.github.io/common-words/#?lang=go The top four most common words are "err", "if", "return", "nil". These are each more common than "func" and "string" combined. It's hard to square Pike's comment with that evidence. I don't know if the try proposal is a good one or not, but I think it's pretty clear that Go's original approach to error handling is quite verbose. Whether it should be that verbose is an interesting question, but personally I think making the user repeat that exact same boilerplate every time adds little value. If you want code that can fail to be visible, at least make the boilerplate shorter, which I guess the "try" proposal accomplishes.
- skybrian 7y agoThese words are commonly used individually, but that says nothing about how often they appear in a particular order.
- blondin 7y agohave you tried clicking on that link?
- enneff 7y ago> The top four most common words are "err", "if", "return", "nil". These are each more common than "func" and "string" combined. It's hard to square Pike's comment with that evidence. Each of those words are extremely common in Go code, even outside of the 'if err != nil { return err }` construct. It makes sense they'd be more common than 'func' and 'string' because functions usually contain at least one if statement and return statement, and err is probably the most common variable name, and nil is used to represent the zero value of many different types. The 'string' word is only really used in struct fields, function signatures, and some variable declarations, but usually the string type is inferred on assignment.
- cfors 7y agoThis will be legal with the proposed `try` statement [0]: info := try(try(os.Open(file)).Stat()) I'm worried about nested versions of this and having to unpack them when reading code, which at the current moment has a much easier imperative block structure. [0] https://github.com/golang/proposal/blob/master/design/32437-try-builtin.md#properties-of-the-proposed-design https://github.com/golang/proposal/blob/master/design/32437-...
- pcwalton 7y agoI've never seen this come up as an issue when reading Rust, which has the same feature being proposed for Go (and then later shortened it to just a single character, ?).
- cfors 7y agoMaybe I am caught up in the "not familiar is hard" look of it and will come around. You are most likely correct :)
- Dylan16807 7y ago? is a big improvement over try specifically because you don't have to unpack nested statements. Everything flows left to right.
- tgsovlerkhgsel 7y agoYou're right, that's horrible. However, you can also write it like this: f := try(os.Open(file)) info := try(f.Stat()) This can be further improved by applying special syntax highlighting that makes the try less prominent. Meanwhile, the cleanest way to write it right now seems to be: f, err := os.Open(file) if err == nil { return err } info, err := f.Stat() if err == nil { return err } That's 8 lines of code to do the same thing. Did you spot the bug I introduced, or did you miss it because the volume of code made you skim? (error check has == instead of !=)? If you want to judge code by the worst thing you can do, you'd need to compare with things like: var info os.FileInfo if f, err := os.Open(file); err != nil { info, err = f.Stat() } if err != nil { return err } (Did you spot the bug? If err is already declared somewhere further up, this will compile <https://play.golang.org/p/0l-SsEbKQh2> https://play.golang.org/p/0l-SsEbKQh2>, but the "err" within the if shadows the previously declared one, so the errors from os.Open and f.Stat are never checked.)
- guessmyname 7y agoBefore commenting, please read the detailed design document [1] and see the discussion summary as of June 6 [2], the summary as of June 10 [3], and specifically the advice on staying focussed [4]. Your question or suggestion may have already been answered or made. Thanks — ATT: Robert Griesemer --- I like writing “if err != nil { … }” so while I disagree with the proposal to add the error check function “try()” I will keep an open mind because I do not have the technical literacy as @griesemer or other people in the Go community to propose something better. I’ll experiment with “try” a few times in personal projects, but I can see myself writing “if err != nil” for several years unless I find a more compelling reason to change, same reason why my team and I haven’t adopted “go mod” despite having Go v1.12.6 (latest stable version as of today) in all our production servers. [1] https://github.com/golang/proposal/blob/master/design/32437-try-builtin.md https://github.com/golang/proposal/blob/master/design/32437-... [2] https://github.com/golang/go/issues/32437#issuecomment-499261947 https://github.com/golang/go/issues/32437#issuecomment-49926... [3] https://github.com/golang/go/issues/32437#issuecomment-500613160 https://github.com/golang/go/issues/32437#issuecomment-50061... [4] https://github.com/golang/go/issues/32437#issuecomment-501878888 https://github.com/golang/go/issues/32437#issuecomment-50187...
- someone7x 7y ago> I like writing “if err != nil { … }” That idiom was my biggest turn off in learning Go. I would be 100x happier with "if not err {...}"
- Dylan16807 7y ago> effort to understand exactly what those 5% of Go developers meant when they said they wanted improved error handling > If you look closely, error handling is not even in the top 3 challenges faced by developers, it’s number 5 Nonono, that's not what those numbers mean. 5% said it was their absolute biggest problem. For all you know it could be the #2 problem of 90%.
- staunch 7y agoI'm glad this post (and others) are sounding the alarm. Go's greatness could very easily be destroyed by a small number of missteps like this one. I'm wishing for the absolute rule of the curmudgeony quadrumvirate like the one that designed Go. This feature-bike-shedding hungry mob is proof of the problem with democracies. And when it comes to programming languages (unlike societies) the the trade-offs for a democracy are not worth the price. Go should (almost) completely ignore the crowd on design issues. It should have changes made that a small cabal of experts unanimously agree with.
- tomohawk 7y agoI've heard people complain about the explicit error handling in go, but that is mostly because they are coming from other languages such as java which have inferior error handling that lets them write 'neater' code, but which generally results in less than robust error handling. Picking on Java, it has checked exceptions, unchecked exceptions, and errors. It's basically a minefield of complexity leading to undefined behavior and/or misbehaving error legs. I can't tell you how many times I've seen InterruptedException mishandled, Throwable (which includes VirtualMachineError) caught with no appropriate handling (quick - what is the appropriate handling of a VirtualMachineError?), or exceptions allowed to wildly propagate.
- kjeetgill 7y ago> java which have inferior error handling that lets them write 'neater' code, but which generally results in less than robust error handling Wowza, that's a strong stance. Look, I'm a fan of Go and Java is definitely aged in a lot of places but this is one of the most bizarre claims I've seen. Criticism of Java's exceptions come from both sides, some people who hate unchecked exceptions so "anything can throw" (same reason C++ camp often avoids exceptions); or that checked exceptions are stupid since you can't meaningfully fix Interruptions or IOExceptions so it's verbose and meaningless to force local catches; they almost always need a rethrow. Both of these criticism are fair because in the end they both make sense sometimes and thus are misused for one another occasionally. We'd all like one answer consistently applied but we don't have it here. Error codes formalized as a part of an API have their place but I find their utility is much more niche than people give them credit for. Why should I decode error codes when a String and a Trace will do? Hint: only when errors have formal semantics such as within a protocol. How I handle the error is partially decided by spec. But to say that in comparison to Go? Go has its normal err mechanism and panic/recover. err is a huge step up from C style errno/manual checking. In practice, Go's err is embarrassingly used just like a checked exceptions: observe and ignore/log or propagate. You end up just unwinding the stack manually, losing the trace, maybe adding context occasionally, like 70% of the time. You handle it where it's meant to eventually, sure. Like everybody does, when it is done right. panic/recover is just unchecked exceptions all over again anyway. They seem to be treated as voodoo idiomatically, sure, but they're there. Go is a great language that brought some really good language runtime features together in a pretty tidy package. Besides maybe defer, which is pretty clean, error handling just isn't a part of the language that got the polish that other parts of the language got on the first pass.
- ridaj 7y agoThe way errors are handled in go feels like the people were thinking hard "let's not repeat the horror of C++ exceptions" and are ok with ugly warts so long as they're not uglier than exceptions... It's clear that there's way too much boilerplate in go procedures that deal with error handling by systematically bailing and passing the failure upstack... But the most confusing thing to me about try() is that, although it's shaped like a function, it actually returns from the current scope on error. It's dangerous syntactic sugar IMO to make this one function-call-like feature not behave like an actual function call...
- atombender 7y agoToo late, Go already has panic(), which is a magical function that unwinds the stack.
- ridaj 7y ago! So it's legal to write something like... panic(panic()) or a := try(try(f())) ...?
- atombender 7y agopanic() doesn't have a return value, so no. But try() has.
- knodi 7y agoStop fighting it embrace it. Error checking in go is one of my fav part of go.
- guidovranken 7y agoI don't write a lot of Go but I have fuzzed a reasonable amount of it. One of the most common types of bugs I encounter are slice out-of-bounds errors. In Go, this invariably leads to immediate program termination (panic). Especially parsers of serialized data received over the wire (like protobufs) are susceptible to slice OOB bugs because the programmer needs to reason about lengths, offsets and integer wraparounds, and this is often hard to get exactly right. Due to the combination of parsing untrusted data, the likelihood of bugs and flat-out crashes if there is a bug, network-facing Go software is especially prone to very low-effort denial-of-service attacks. Python and Java got this right: everything throws an exception, including out-of-bounds access (IndexError, ArrayIndexOutOfBounds), so by wrapping your whole application in a try/except block you can eliminate a whole class of otherwise fatal errors. Unless I missed something, the upcoming change isn't going to alter the handling of OOB's, which seems like a missed opportunity because a fully-fledged try/catch mechanism could effectively defuse many bugs.
- tech_dreamer 7y agoIn Java land checked exceptions are considered to be an anti pattern for sometime. If I remember correctly one of the major change in Hibernate ORM 3.0 was converting checked exceptions to runtime equivalents (ie, caller is free to disregard the exception) (this happened 10-12 yrs ago). Coming back to Golang, you get the same behaviour if you are not checking `error is nil` condition
- apta 7y ago> In Java land checked exceptions are considered to be an anti pattern for sometime. It depends on whom you ask. Some people quite like checked exceptions. Either way, both checked and unchecked exceptions are superior to golang's approach to error handling.
- bmm6o 7y agoNot sure what you mean by "free to disregard", but the exception being unchecked doesn't fundamentally alter the control flow of a thrown exception. It only affects type checking - hence the name.
- thr23d93 7y agoI find the logic the article uses to make its point a bit handwavy, or you could even say "wrong". If the language specification required the first line to start FIRST and then every subsequent line in each file start with AND THEN, so that this: package main import ( "fmt" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, you've requested: %s\n", r.URL.Path) }) http.ListenAndServe(":80", nil) } becomes FIRST package main AND THEN AND THEN import ( AND THEN "fmt" AND THEN "net/http" AND THEN ) AND THEN AND THEN func main() { AND THEN http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { AND THEN fmt.Fprintf(w, "Hello, you've requested: %s\n", r.URL.Path) AND THEN }) AND THEN AND THEN http.ListenAndServe(":80", nil) AND THEN } there is a very good chance it would not make it into "the biggest challenge you personally face using Go today." Because it's not a challenge. It's stupid, but not a challenge. So just because the verbose incantation if err != nil { return err } or other issues, could be thought of as very similar to AND THEN, it doesn't mean that this is the biggest challenge someone personally faces. it could be stupid, but you get used to it. so it depends on the wording of the question. Basically the real question isn't how big of a pain point it is. It's how much it could be fixed. my specification for the formatting of the language would be hugely improved by removing the AND THEN line from each line of the code. It's kind of ugly.
- tgsovlerkhgsel 7y agoIt would also probably not come up in surveys, because the only people using the language would be the ones who are OK with it - others would simply take a look at it, conclude that having a pointless "AND THEN" everywhere is just too ugly, and move to a language that made better choices.
- rsc 7y agoFWIW, I wrote a short response here: https://twitter.com/_rsc/status/1146128393542492160 https://twitter.com/_rsc/status/1146128393542492160 I want to flag especially that there is not, nor has there ever been, a plan to "push this through". People consistently say error handling is problematic for them in Go. Overall I think people spend more time writing error checks than they should, and at the same time there are still too many mis-handled errors. We would like to see if we can find a way to make it both less work and more correct. Maybe we can, maybe we can't. The process is slow and needs to backtrack out of formerly-promising dead ends, and that's OK. There's a very large amount of conversation right now around try, and that's good. Like I said in the tweets, community-wide discussions like this one are open source at its best.
- tmaly 7y agoJust curious, why a twitter thread response and not a blog post?
- pfarnsworth 7y agoI think "try" is a terrible name, because it overloads try/catch which is very common usage these days but it's nothing like that. It's basically a error checking macro, so give it a new name.
- Sphax 7y agoRust had the try! macro before which is similar, the name is fine I think.
- willtim 7y agoWhy not allow call-by-name parameters to functions? That would enable library authors to build whatever error handling conveniences they wanted. This feature dates all the way back to ALGOL-60.
- Cthulhu_ 7y agoI think you're answering your own question there: > That would enable library authors to build whatever error handling conveniences they wanted What I want from a language - especially if it's, like Go, aimed at really big project - is for it to be opinionated and narrowed in options. That's Bill Kennedy's point as well, they're adding a language level feature so now there's one more way to do a very common thing. And when there's multiple ways to do something, they will all get used. "But what about conventions and code reviews?", you might ask; that's cognitive overload that, if there was only one way, would never be a thing. I mean another feature of Go is that it enforces a certain standard (with tooling and formatters), so that as a development team you should never have to waste time and energy on discussing or arguing about formatting. I'm not against changing how errors are handled now, as long as they're standardized and the One Way to do things.
- apatheticonion 7y agoI wouldn't like to see a change to error handling, I would like to see generics added (in the form that was described in the Sydney talk). Maybe a stack trace would be nice in the errors, though
- amluto 7y agoI am not a Go programmer, but: The article suggests that try() isn’t solving a big problem. If I were a Go programmer, I think I would want a bigger change, specifically, a proper sum type for errors. In Go, the convention is to return a result and an error despite the fact that essentially every function that can return an error wants to return a result or an error. This results in complexities in the proposal about what the result should be when try() causes an error return. The sensible answer is that there should not be a result. The way that Rust (and Haskell and many other languages) do so much better than Go has little to do with fancy ? operators. It’s that the return type makes sense. Of course, sum types without genetics would be odd, but I don’t see how this would stop Go — a special case specifically for “such-and-such type or error” seems consistent with the Go typing philosophy.
- kjeetgill 7y agoI think it's funny that you mention a bigger change but sum-types are 80% of what Go already has here. While it's true that it solves the ambiguity issue of representing `Either Result or an Error But Not Both` instead of the `Result or Error or Both`; that doesn't solve the issue that anyone actually has, which is that most errors are handled with if err != Nil { return err; } after every other line sometimes. It's verbose, manual, and doing the helpful thing like adding context for the error is repetitive and often omitted. As I've mentioned elsewhere, you essentially want an exception system. Some care still needs to be taken with how other language features interact with it. You'll probably want a sum-type-y way to catch exceptions as an expression eventually. What happens if exceptions are thrown from functions in defers, etc. But unlike more FP languages where error propagation is much easier in a soup of composed functions, Go is much more Java/C#-like. Most functions have much more important names and meaning which make stacktraces much more valuable.
- tgsovlerkhgsel 7y ago> biased because only those who had a problem submitted proposals and this leaves out all of the developers who don’t consider error handling in Go needs to be better It's probably also biased due to the people who gave up on Go completely because they saw it as a sufficiently major issue and/or had little faith in Go ever improving (I can't exactly put a finger on it, but a lot of the decisions in Go seem to be backed by "... and if you don't like our approach, you're WRONG").
- hu3 7y ago> a lot of the decisions in Go seem to be backed by "... and if you don't like our approach, you're WRONG" I don't understand this complain. Ultimately that's how most if not all programming languages are developed. A few individuals act as guide and gatekeepers and that's fine.
- mleonhard 7y ago> "if you don't like our approach, you're WRONG" This was also my experience interacting with the Golang team while working at Google.
- kstenerud 7y agoI was never a fan of try. It's too magical and breaks the flow. Far better to use something more explicit and controllable: f, err := os.Open(filename) onerr return 0, err which is just syntactic sugar for: f, err := os.Open(filename) if err != nil { return 0, err } also: err := DoSomething() onerr { fmt.PrintF("We got error %v\n", err) return 0, err }
- cbhl 7y agoI wonder if Go just needs syntactic sugar that's similar to the RETURN_IF_ERROR that's common in Google C++ code (for example, in protobuf: https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/stubs/status_macros.h#L49 https://github.com/protocolbuffers/protobuf/blob/master/src/...)
- nikolay 7y agoAll the try(), catch(), and onerr proposal are ugly patchworks. All I need is to be able to skip the != nil and just be able to write: if err { ... }