19 ms·
(On | No) Syntactic Support for Error Handling
- codr7 1y agoI just wish the could stabilize the compiler before piling on more features. I regularly run into internal compiler errors these days for pretty normal looking code. It's getting to the point where I'm reluctant to invest more time in the language right now. UPDATE: See comment below for full error message and a link to the code.
- johnfn 1y agoIn that case, you might enjoy this part of the article: > For the foreseeable future, the Go team will stop pursuing syntactic language changes for error handling
- Thaxll 1y agoI've never seen a single internal compiler issue in 10 years of working in Go. What error are you talking about?
- shivamacharya 1y agoIf you do stuff the language doesn’t support, it’s not the languages problem.
- codr7 1y agoI did nothing weird, played around a bit with the new iterators. Internal compiler errors are very much the implementation's problem. UPDATE: See comment below for full error message and a link to the code.
- shivamacharya 1y agoI only say this because I have yet to encounter a single internal compiler error in years of writing Go professionally. I can’t conceive of the kind of code one must be writing for internal compiler errors to be a repeated issue.
- deleted 1y ago[deleted]
- codr7 1y agoSo here's the complete error message: <unknown line number>: internal compiler error: unexpected types2.Invalid Please file a bug report including a short program that triggers the error. https://go.dev/issue/new https://go.dev/issue/new And here's the code that triggers it: https://github.com/codr7/shi-go/blob/main/src/shi/call.go https://github.com/codr7/shi-go/blob/main/src/shi/call.go The code is never referenced in the project, but running make in the project root with this file in it triggers the error. Remove the file and the error disappears. Happy now?
- kiitos 1y agoPaste exactly what commands you run and exactly their output, including exactly the rev of the repo you're running them in. > Remove the file and the error disappears Remove the file and the code no longer compiles, because the file contains definitions that are used by other code in the package. If removing that file doesn't break your build, something is wrong with your build! Your Makefile seems to be calling `go test src/tests/*` which is invalid syntax, I suspect that's just one of many similar kinds of mistakes, and likely indicative of a misunderstanding of the language tooling... > https://github.com/codr7/shi-go/blob/main/src/shi/call.go https://github.com/codr7/shi-go/blob/main/src/shi/call.go This code is buggy from tip to tail, my goodness! Starting with no `gofmt` formatting, everything in https://github.com/codr7/shi-go/blob/main/src/shi/vm.go https://github.com/codr7/shi-go/blob/main/src/shi/vm.go, invalid assumptions in everything that embeds a Deque, no meaningful tests, misuse of globals, the list goes on and on... ! It seems like you're programming against a language spec that you've invented yourself, maybe influenced by Go, but certainly not Go as defined!
- stefanos82 1y agoI have hard time understanding why they didn't go with func printSum(a, b string) error { x := strconv.Atoi(a) or { return error } y := strconv.Atoi(b) or { return error } fmt.Println("result:", x + y) return nil } or something along these lines...
- alanbernstein 1y agoSeems like it's only worth the cost of the change if it removes all three verbose lines per check, this only removes one.
- wredcoll 1y agoOh cool, you've reinvented perl.
- righthand 1y ago> Unfortunately, as with the other error handling ideas, this new proposal was also quickly overrun with comments and many suggestions for minor tweaks, often based on individual preferences. Ian closed the proposal and moved the content into a discussion to facilitate the conversation and to collect further feedback. A slightly modified version was received a bit more positively but broad support remained elusive. > After so many years of trying, with three full-fledged proposals by the Go team and literally hundreds (!) of community proposals, most of them variations on a theme, all of which failed to attract sufficient (let alone overwhelming) support, the question we now face is: how to proceed? Should we proceed at all? > We think not.
- shivamacharya 1y agoIf you do this, returning the error last is now part of the language rather than a convention. You’d be making a pretty large language change.. and for what? One line of code that’s already folded away by any modern editor?
- arp242 1y agoYou need to assign the error to a variable, probably. So it would have to be more something like: n := strconv.Atoi(s) or |err| { return fmt.Errorf("foo: %w", err) } n := strconv.Atoi(s) or |err| { if !errors.Is(err, pkg.ErrFoo) return fmt.Errorf("foo: %w", err) } } Just "error" (which shadows the built-in type) won't really work. I'm just making up syntax here to illustrate the point; doesn't look too brilliant to me. A func might be a bit more "Go-like": n := strconv.Atoi(s) or func(n int, err error) { return fmt.Errorf("foo: %w", err) } All of this is kind of a moot point at Robert's blog post says that these proposals won't be considered for the foreseeable future, but IMHO any error handling proposal should continue to treat errors as values, which means you should be able to use fmt.Errorf(), errors.Is(), mylogger.Error(), etc.
- 827a 1y agoIMO: The position of "we aren't sure what the right approach to improvement is so we aren't going to do anything" has killed far bigger and more important projects, companies, and even countries, than Golang. Adapt or die; the world isn't going to wait for you. (I love the Go team, and appreciate everything they do. I'm just sad to see a language I used to love fail to keep pace with many of the other options out there today.)
- justin66 1y agoGo adoption has only increased over time.
- 827a 1y agoThere's no methodologically sound way to measure its popularity available to most people to make an argument on its popularity one way or the other. That's why I didn't, and that's why you shouldn't either.
- justin66 1y agoIf you say so, but the concern you floated (The position of "we aren't sure what the right approach to improvement is so we aren't going to do anything" has killed far bigger and more important projects, companies, and even countries, than Golang. ) is fundamentally silly, given how long Go has been in business and seemingly thriving while applying this approach to a few select, controversial features. If it was going to be killed by this approach, it would now be dead.
- MeetingsBrowser 1y agoChanging too quickly is a much bigger problem. It may not be ideal, but I think leaning towards being slow makes sense in this context. Every person/company using Go chose to use it knowing how errors are handled. Each new way of error handling seems to upset a large number of users, some of which may not have chosen Go had the newer system been in place originally. If it is impossible to know which choice is correct, at least everyone has some baseline level of acceptance for the status quo.
- righthand 1y agoHopefully this is the final nail in the coffin for all the “but I have to handle my errors” whining.
- aystatic 1y agoI don't know that there's whining about "having to handle errors" in principle, it's pretty clearly a complaint with the syntax and semantics of doing so Some languages even make omitting error handling impossible! (e.g. Result sum types). None have anywhere near the amount of "whining" Go seems to attract
- maxwellg 1y agoThis is the right move for Go. I have grown to really love Go error handling. I of course hated it when I was first introduced to the language - two things that changed that: - Reading the https://go.dev/blog/errors-are-values https://go.dev/blog/errors-are-values blog post (mentioned in the article too!) and really internalizing it. Wrote a moderately popular package around it - https://github.com/stytchauth/sqx https://github.com/stytchauth/sqx - Becoming OK with sprinkling a little `panic(err)` here and there for truely egregious invalid states. No reason forcing all the parent code to handle nonsense it has no sense in handling, and a well-placed panic or two can remove hundreds of error checks from a codebase. Think - is there a default logger in the ctx?
- deleted 1y ago[deleted]
- masklinn 1y agoThis is just sad. Neither of your supports have anything to do with how dismal Go's error handling is, and neither would be worsened in any way by making it better. If anything they would be improved.
- pas 1y agoEven PHP has better error handling with the levels, and the @ (at operator) to suppress errors at a callsite. Even bash has -e :)
- waynerad 1y agoI've been programming in PHP since 2002 and Go since 2011. At work I work primarily with two large PHP codebases, 1 about ~half a million lines of code, and the other about ~3 million lines of code. I'm porting PHP code to Go and writing some new code, like cron jobs, in Go. There's about 55,000 lines of Go code at this point. What I have learned in this time is: Go is a very good, very high quality, very well designed language. PHP is a terrible, terrible, terrible language -- at least if your mission is creating highly reliable software. If your goal is rapid prototyping of the visual appearance of a webpage, PHP is good for that -- that's what it was originally invented for, back in the 1990s, and it's still the best language for that specific use case. In PHP, if you are looking at a line of code, it's impossible to tell what happens if an error occurs. There's an error_reporting level that can be changed anywhere else in the codebase at any time. So an error might be thrown in the user's face, or not -- depending on the error_reporting level and what the error is. This can also interact with output buffering. (I guess if the "@" sign is present, at least then you know output of an error message is suppressed.) There's a error_handler function that could be set. Oh but it gets worse! Even if you have the entire codebase and can scour every line of code, and trace every possible execution path, you still can't tell what will happen if an error occurs at the line of code you are looking at -- because there are php.ini settings that come into play! This is without even mentioning the try/catch exception handling system, which PHP also has, and that you think is such a good thing. So if an error happens on the line you are looking at, execution may switch to somewhere above you in the call stack. But (at least in theory) if you have the complete source code, you can figure out all the places where that might be. This is an absolute nightmare if you care about reliability. The worst thing you could possibly have in a programming language if you care about reliability is to be unable to tell what happens when an error occurs and reason about the program's behavior. Contrast this with Go. In Go, I can know what happens if an error occurs because it's right there. There's an "if err != nil {..." block that tells me exactly what happens. By porting code to Go, I've been able to increase the reliability tremendously. The thing about go, is that using Go doesn't automatically give you reliability -- you have to learn the techniques and tools in Go that give you reliability. But once you do that, the quality of software you can produce is vastly higher. I've spent the last decade or so learning this. Learning how to structure the code to make maximum use of the compiler's static type checking to catch errors. Making use of the static analysis tools that catch errors. Using a combination of errcheck and staticcheck (mentioned elsewhere in this discussion), you can guarantee every err return value is actually checked and handled. So the oft-cited language flaw of Go allowing you to forget to handle errors becomes a non-issue. Go has built-in support for unit tests and the excellent polymorphism system makes tests easier to make than in PHP. And, getting back to the topic at hand, in Go, I created my own system for handling the err values that get returned so junk errors created by hackers trying to find security vulnerabilities on our server get filtered out, while actual errors that I need to fix get logged and brought swiftly to my attention. Can you do something similar in PHP? In theory, perhaps, but we are to afraid of breaking things to try to massively refactor our ~2 million lines of PHP code in order to do that. So we have various log files and database entries that get clogged with errors, and sometimes we notice errors that we need to fix, but usually we don't. Usually we don't know anything is wrong until we get customer complaints on the Help Desk. Anyway, I'm glad the Go team rejected the idea of changing Go's error handling. Is Go's error handling verbose, tedious, and repetitive? Yes. But it's also unambiguous and gives you total control over how your program responds when an error occurs, which is exactly what you want if you want to write software with the maximum reliability. Don't just take my word for it. Notice how lots of "cloud infrastructure" is written in Go. Kubernetes is written in Go, Docker is written in Go, Terraform is written in Go, etc. Yes, I know some people, like Facebook, have managed to write decently reliable code in PHP. But I suspect Facebook has thrown massive amounts of dollars and people at the problem. Various other PHP projects, like certain website creation systems that shall not be named, have a reputation for being buggy. Sorry, I couldn't let you say PHP has better error handling without a response. It may be "better" for having more compact, prettier looking code. But it's not better for writing actually reliable software. If you want to write actually reliable software, Go is way better.
- marcoc 1y agoNow that I think about it, are there any color schemes or extensions that highlight the error handling logic differently so that one can better focus on the “main” logic flow of the code while the error handling logic is still there?
- Refreeze5224 1y agoI would love something like this, and if it exists, I've not come across it. Offloading a way of differentiating error handling syntax vs. normal code to the IDE seems like a nice way of handling this issue.
- renewiltord 1y agoGoland folds it visually partially https://github.com/golang/vscode-go/issues/2311 https://github.com/golang/vscode-go/issues/2311
- rollcat 1y agoYou would have to infer the intent of the code. One example, from a small project I'm working on: $ find . -name "*.go" | xargs grep 'if err !=' | wc -l 242 $ find . -name "*.go" | xargs grep 'if err ==' | wc -l 12 So about 5% of the error checking code is about handling the edge cases, where we are very much interested in what the error actually is, and need to handle those conditions carefully. If you discard that as "error handling noise", you're in for a bug. Which is, by the way, perhaps the worst side-effect of verbose, repetitive error handling. Apropos syntax highlighting: many themes in regular use (certainly most of the defaults) choose a low-contrast color for the comments. The comments are often the most important part of the code.
- Refreeze5224 1y agoI don't really understand this decision. They know from developer surveys that verbose and repetitive error handling is literally the number 1 issue. Seeking the perfection of syntax that everyone agrees on seems to be the enemy of providing some good alternative to the status quo. Their comment about providing some new syntax and people being forced to use it seems off base to me. It's nice to not have multiple ways of doing things, but having only 2 when it comes to error handling does not seem like a big deal. I imagine people will just use their preference, and a large percentage of people will have a less verbose option if they want it.
- munificent 1y ago> They know from developer surveys that verbose and repetitive error handling is literally the number 1 issue. Agreement on a problem does not imply agreement on a solution. It's not about perfection. It's about not having a solution that gets anywhere near a majority approval. Let's say your neighborhood has an empty plot of land owned by the city that is currently a pile of broken chunks of concrete, trash, and tangled wire. It's easy to imagine that there is unanimous agreement by everyone in the neighborhood that something better should be placed there. But the parents want a playground, the pet owners want a dog park, the homeless advocates want a shelter, the nature lovers want a forest, etc. None of them will agree to spend their tax dollars on a solution that is useless to them, so no solution wins even though they all want the problem solved.
- Grikbdl 1y agoEven if people in your example couldn't agree on a particular alternative, the outcome still is a less attractive area, maybe some will move out and fewer people move in. So, any solution would be better than the status quo - and they all would probably agree on that. The lack of a good error handling story to a lot of people puts go in a mental trash bin of sorts. Similar (but different) reasons eg Java goes to a mental trash bin. I think leaving this issue unhandled will only make go look worse and worse in comparisons as the programming language landscape evolves. It might take 10 or 20 years but it'll always be unique in having "trash bin worthy" error handling. (this can perhaps be argued - maybe exceptions are worse, but at least they're standard).
- rco8786 1y agoThis feels like it's making it worse lol
- rollcat 1y agoSnip: if err != nil { return fmt.Errorf("invalid integer: %q", a) } Snip. No syntax for error handling is OK with me. Spelling out "hey I actually do need a stack trace" at every call site isn't.
- skydhash 1y agoYou actually don't. In mistakes #52 "Handling an error twice" from the book "100 Go Mistakes and How to Avoid Them" by Teiva Harsanyi, the recommendation is to either return an error to the caller or handle the situation (and maybe logging it). Sometimes you wnat some extra information as to why it's an error, so you wrap it. Go forces you to be explicit about error handling. Java syntax is not that much better. JavaScript, Kotlin, Swift,... is more about avoiding null pointer exception than proper error handling.
- rollcat 1y agoI return the error to the caller. The caller returns it to their caller. 5 frames up, someone gets a [syscall.EINVAL], and has to figure out what to do about it. Perhaps it's time to log it? If I had to write my own "100 mistakes" book, "assuming the callee knows what to do" would be somewhere in the top 20, down below "I won't need to debug this".
- skydhash 1y agoIt's all about designing software. The callee is the one encountering the error, not any of the caller up in the stack trace. Somewhere in the call chain, there's a need to take a decision. So you, as the developer, decide where that needs to be. It may be at the callee level (like an exponential retry) or at the caller level (display an error message). In the later case, you may want to add more information to the error data block, so that the caller my handle the situation appropriately. So if you want tracing, you just need to wrap the error and returns it. Then your logging code have all the information it needs: like [error saving file [permission error [can't access file]]] instead of just [syscall.EINVAL].
- zb3 1y agoThankfully repetitive language is less of a problem now that we have AI. The current syntax is just "add error handling to this function" :)
- Jtsummers 1y agoYou're getting downvoted, but this was what tptacek basically wrote about. Key points from his blog are that LLMs are good at tedium, and Go's structure is highly repetitive and amenable to LLM generation. The error handling tedium is probably part of why it's highly repetitive. > I work mostly in Go. I’m confident the designers of the Go programming language didn’t set out to produce the most LLM-legible language in the industry. They succeeded nonetheless Go has just enough type safety, an extensive standard library, and a culture that prizes (often repetitive) idiom. LLMs kick ass generating it. https://news.ycombinator.com/item?id=44163063 https://news.ycombinator.com/item?id=44163063 - 2386 comments
- homebrewer 1y agoWriting it was never the problem if you're using proper tools, e.g. an actual IDE (IDEA does fine), or at least a snippet manager for your text editor. Inserting a wrapping error handling snippet requires two key presses. It's reviewing mountains of that crap that's the problem, especially if there are non-trivial cases hidden in there, like returning the error when `err == nil` (mentioned by others in this thread).
- whstl 1y agoI used to hate the repetitive nature of Go’s error handling until I was burned by bad/mysterious error messages in production. Now my error handling is not repetitive anymore. I am in peace with Golang. However I 100% get the complaint from the people who don’t need detailed error messages.
- DangitBobby 1y agoYou probably wouldn't have had the bad/mysterious error messages in production if they were just stack traces to begin with.
- danenania 1y agoStack traces are full of noise by comparison and don't have context added by the programmer at each frame. For me, Go error chains are much easier to work with. I can see the entire flow of the error at a glance, and can zero in on the relevant call in seconds with a single codebase search.
- DangitBobby 1y agoStack traces are not so long that you can't find the information you need in them, and actually just like go in some languages you can elect to add context to your stack trace (e.g. in python by raising an error from another error). My experience in go was opposite of yours. The original devs (who were long gone) provided no information at all at the error site and I felt lucky even to find the place in the code that produced the error. Unfortunately the "force you to handle errors" idea, while well intentioned, doesn't "force you to provide useful error handling information", making it worse than stack traces by default.
- danenania 1y agoYou're right that its usefulness is contingent on adding helpful context to errors. Without that, I might agree that stack traces are better.
- 1y ago
- arp242 1y ago> Of course, there are also valid arguments in favor of change: Lack of better error handling support remains the top complaint in our user surveys. Looking at that survey, only 13% mentioned error handling. So that means 87% didn't mention it. So in that sense, perhaps not too much weight should be given to that? I agree the verbosity fades into the background, but also feel something better can be done, somehow. As mentioned there's been a gazillion proposals, and some of them seem quite reasonable. This is something where the original Go design of "we only put in Go what Robert, Ken, and Rob can all agree on" would IMHO be better, because these type of discussions don't really get a whole lot better with hundreds of people from the interwebz involved. That said, I wasn't a fan of the try proposal and I'm happy it didn't make it in the language. And to be honest in my daily Go programming, it's not that big of a deal. So it's okay.
- smw 1y ago"biggest challenge", it's not multiple choice
- throwaway71271 1y agoEverything is fine I dream if err, if err dreams me.
- pie_flavor 1y agoYou draw up a list of checkboxes, you debate each individual point until you can check them off, you don't uncheck them unless you have found a showstopping semantics error or soundness hole. Once it is complete it is implemented and then everyone who had opinions about whether it should be spelt `.await` or `/await` or `.await!()` vanishes back into the woodwork from whence they came. Where's the disconnect? Rust works like this. Sometimes an issue can be delayed for over a decade, but eventually all the boxes are checked off and it gets stabilized in latest nightly. If Go cannot solve the single problem everyone immediately has with the language, despite multiple complete perfect proposals on how to do it, simply because they cannot pick between the proposals and are waiting for people to stop bikeshedding, then their process is a farce.
- hu3 1y ago> Go cannot solve the single problem everyone immediately has with the language... What? Survey says 13% mentioned error handling. And some people actually do prefer it as is. https://go.dev/blog/survey2024-h1-results https://go.dev/blog/survey2024-h1-results
- judofyr 1y ago13% mentioned that error handling was the biggest challenge with using Go. This was not a multiple choice question, but you had to pick one answer. We don't know how many people would consider it challenging. (This is typically why you have a 1-10 scale per choice.)
- joaohaas 1y agoThis doesn't mean the rest of the 87% enjoy it. Honestly, I'd rather the next survey included a question "are you satisfied with the current error handling approach"
- 9rx 1y agoI'm as satisfied with the error handling approach as I am for the email address handling approach, the time of day handling approach, the temperature handling approach, etc. But that doesn't imply that I am satisfied. I do believe there is a lot of room for improvement. Frankly, I think what we have is quite bad. Framing it as something about errors misses the forest for the trees, though. How would I respond to your query without misleading the reader?
- henry700 1y ago>For a while, the lack of generics surpassed complaints about error handling, but now that Go supports generics, error handling is back on top >The Go team takes community feedback seriously It feels like reading satire, but it's real.
- danenania 1y agoThey clearly are wrestling with these issues, which to me seems like taking the feedback seriously. Taking feedback seriously doesn’t imply you have to say yes to every request. That just gives you a design-by-committee junk drawer language. We already have enough of those, so personally I’m glad the Go team sticks to its guns and says no most of the time.
- ummonk 1y agoHow is Go not a design-by-committee language? They don't have a single lead language developer or benevolent dictator, and as this blog demonstrates, they're very much driven by consensus.
- danenania 1y agoTrue, but they’re very picky as committees go. But yeah, maybe not the best use of that expression…
- JamesSwift 1y agoI havent followed this argument closely so forgive me if I'm missing relevant discussion, but I dont see why the Rust style isnt just adopted. Its the thing I immediately add now that I have generics in Go. I only see this blurb in a linked article: > But Rust has no equivalent of handle: the convenience of the ? operator comes with the likely omission of proper handling. But I fail to see how having convenience equates to ignoring the error. Thats basically half of my problem with Go's approach, that nothing enforces anything about the result and only minimally enforces checking the error. eg this results in 'declared and not used: err' x, err := strconv.Atoi("123") fmt.Println("result:", x) but this runs just fine (and you will have no idea because of the default 0 value for `y`): x, err := strconv.Atoi("123") if err != nil { panic(err) } y, err := strconv.Atoi("1234") fmt.Println("result:", x, y) this also compiles and runs just fine but again you would have no idea something was wrong x, err := strconv.Atoi("123") if err != nil { } fmt.Println("result:", x) Making the return be `result` _enforces_ that you have to make a decision. Who cares if someone yolos a `!` or conveniently uses `?` but doesnt handle the error case. Are you going to forbid `panic` too?
- School-Cotton 1y agoGo can’t have Result because they don’t have sum types, and they can’t add them because of their bizarre insistence that every type has to have a designated zero value.
- masklinn 1y ago> they can’t add them because of their bizarre insistence that every type has to have a designated zero value. Nothing prevents adding union types with a zero value. Sure it sucks, but so do universal zero values in pretty much every other situation so that's not really a change.
- School-Cotton 1y agoMaking it so all sum types have to be nillable would make them dramatically worse (the basic motivating example for sum types is Option, the whole point of which is to get rid of NULL). I guess this is in agreement with your point.
- _jab 1y agoI once had a Go function that, unusually, was _expecting_ an error to be returned from an inner function, and so had to return an error (and do some other processing) if none was returned by the inner function, and return nil if the inner function did return an error. In a nutshell, this meant I had to do `if err == nil { // return an error }` instead of `if err != nil { ... }`. It sounds simple when I break it down like this, but I accidentally wrote the latter instead of the former, and was apparently so desensitized to the latter construct that it actually took me ages to debug, because my brain simply did not consider that `if err != nil` was not supposed to be there. I view this as an argument in favor of syntactic sugar for common expressions. Creating more distinction between `if err != nil` (extremely common) and `if err == nil` (quite uncommon) would have been a tangible benefit to me in this case.
- adamrt 1y agoAny time I write "if err == nil" I write // inverted just to make it stick out. It would be nice if it was handled by the language but just wanted to share a way to at least make it a bit more visible. if err == nil { // inverted return err }
- macintux 1y agoI know diddly/squat about Go, but from similar patterns in aeons past, would "nil == err" work as a way to make it stand out?
- haiku2077 1y agoJust tried this and it appears to be valid in the compiler, formatter and golangci-lint
- _whiteCaps_ 1y agohttps://en.wikipedia.org/wiki/Yoda_conditions https://en.wikipedia.org/wiki/Yoda_conditions Works especially well in languages that can make assignments in if statements, e.g: if foo = 42 { }
- evmar 1y agoMost discussions of language features immediately fall into the politician's syllogism: https://en.wikipedia.org/wiki/Politician%27s_syllogism https://en.wikipedia.org/wiki/Politician%27s_syllogism I appreciate the Go language's general sense of conservatism towards change. Even if you're not a fan of it, I think it's admirable that there is a project staking out a unique spot in the churn-vs-stability design space. There are plenty of other projects that churn as fast as they can, which also has its pros and cons, and it's great to be able to see the relative outcomes. PS: it's kind of hilarious how the blog post is like "there are hundreds of proposals and miles of detailed analysis of these", vs the commenters here who are like "I thought about this for five minutes and I now have an idea that solve everything, let me tell you about it".
- mseepgood 1y agoSometimes doing nothing is the right thing to do. (Quote from Until Dawn) Go chose not to change the error handling - Nature remained in balance.
- ummonk 1y agoI'd happily come up with criticisms of any specific proposal and bikeshed it, but any one of these proposals would be preferable to the status quo. I'd understand if they decided they needed more time to continue iterating on and analyzing proposals to find the right solution, but simply declaring that they'll just suspend the whole effort because they can't come to a consensus is rather infuriating.
- sa46 1y ago“Simply declaring” is inaccurate description of the Go team’s decision. The team built several proposals, reviewed dozens more, and refined the process by gathering user feedback in multiple channels. The Go team thoroughly explored the design space for seven years and did not find community consensus.
- ummonk 1y agoThere are two possibilities. 1) There isn't consensus that improved syntax for error handling is needed in the first place. If that is the case, they should just say so, instead of obfuscating by focusing on the number of proposals and the length of the process. 2) There is consensus about a need for improved error handling syntax, but after seven years of proposals they haven't been able to find community consensus about the best way to add said syntax. That would mean that improved syntax for error handling is necessary, but the Go team is understandably hesitant to push forward and lock in a potentially inferior solution. If that is the case, then would be reason to continue working on improved syntax for error handling, so as to find the best solution even if it takes a while.
- ddoice 1y agoOh No! Is a much better name for error handling.
- ajkjk 1y agoOkay here's my idea, not found on the list in the article, what do you think: You add a visualization sugar via an IDE plugin that renders if/else statements (either all of them or just error cases) as two separate columns of code --- something like x = foo(); if (x != nil) | else <happy case> | <error case> And then successive error cases can split further, making more columns, which it is up to the IDE to render in a useful way. Underneath the representation-sugar it's still just a bunch of annoyingly nested {} blocks, but now it's not annoying to look at. And since the sugar is supported by the language developers, everyone is using the same version and can therefore rely on other developers seeing and maintaining the readability of the code in the sugared syntax. If the error case inside a block returns then its column just ends, but if it re-converges to the main case then you visualize that in the IDE as well. You can also maybe visualize some alternative control flows: for instance, a function that starts in a happy-path column but at all of its errors jumps over into an error column that continues execution (which in code would look like a bunch of `if (x=nil) { goto err; }` cases. Reason for doing it this way: logical flow within a single function forms a DAG, and trying to represent it linearly is fundamentally doomed. I'm betting that it will eventually be the case that we stop trying to represent it linearly, and we may as well start talking about how to do it now. Sugar is the obvious approach because it minimizes rethinking the underlying language and allows for you to experiment with different approaches.
- Someone 1y agoI would simplify that to x = foo() ||| <error case> <happy case> (With the specific symbol used in lieu of ||| to be decided) That is shorter and keeps the happy path unindented, even if it has additional such constructs, for example x = foo() ||| return Error(err, “foo failed”) y = bar() ||| return Error(err, “bar failed”)
- layer8 1y agoI think that IDE functionality is fine for writing code, but shouldn’t be imposed for the UX of reading code, because code reading also happens a lot outside of IDEs, because it constrains the choice of editors, and because it creates fundamentally different “modes” of source code presentation. The visualizations will start to appear in comment threads like this one, and in other publications on the web, but copying them and pasting them into an editor will not work (will be invalid syntax). It creates unnecessary complications across the whole ecosystem. Language syntax should stand on its own, and shouldn’t need crutches like that to make it ergonomic to read.
- zahlman 1y agoWatching the process of thinking about this from the outside, somehow reminds me of my experience on the inside of the Python community trying to figure out packaging.
- te_chris 1y agoThe way elixir conventionally uses tuples and pattern matching is really good.
- mtndew4brkfst 1y agoIt's a pale shadow of an actual Option/Result type, though, and the way most community and professional Elixir code uses ok-tuples is hardly what I would call rigorous. The with special form leads to sloppy pass-the-buck design IME, and nothing in the language design or Credo ruleset is likely to steer anyone to do better.
- threemux 1y agoIf you feel the need (as many have in this thread) to breezily propose something the Go Team could have done instead, I urge you to click the link in the article to the wiki page for this: https://go.dev/wiki/Go2ErrorHandlingFeedback https://go.dev/wiki/Go2ErrorHandlingFeedback or the GitHub issue search: https://github.com/golang/go/issues?q=+is%3Aissue+label%3Aerror-handling https://github.com/golang/go/issues?q=+is%3Aissue+label%3Aer... I promise that you are not the first to propose whatever you're proposing, and often it was considered in great depth. I appreciate this honest approach from the Go Team and I continue to enjoy using Go every day at work.
- anentropic 1y agoIt's probably already answered somewhere, but I am curious why it's such a problem in Go specifically, when nearly every language has something better - various different approaches ... is the problem just not being able to decide / please everyone, or there's something specific about Go the language that means everyone else's solutions don't work somehow?
- ok_dad 1y agoGo has specific goals like not hiding control flow. This would go against those goals, at least the ways people have thought to do it so far.
- tialaramex 1y agoI don't see how Try (the ? operator) is hidden control flow. It's terse, but it's not hidden.
- ok_dad 1y agoI personally agree, but I’m not the go team. The hidden control flow was specifically called out but about the try keyword. I like the ? and similar ways of checking nulls, but personally I don’t mind the verbosity in go, even if there are footguns.
- 1y ago
- unclad5968 1y agoI don't use Go, but I actually like Go's error handling and I think multiple return values is a better solution than any other language I've used. So much so, I've basically adopted it in my c++ code using std::pair. Errors are a value, and the abstraction over that is unnecessary in my opinion. Rust's result type is just syntactic sugar around the multiple return value approach. I don't care for the syntactic sugar, and doing many things in few lines of code isn't valuable to me, but I suspect this is why people love rust's error handling.
- masklinn 1y ago[flagged]
- unclad5968 1y agoI'm certainly open to discussion, but your comment doesn't really have any substance to respond to.
- aystatic 1y agoYou've managed to miss the entire point of using a union: the value is either a success payload or an error value, never both. You can't encode that mutual exclusivity if you return a std::pair or std::tuple. That's exactly why std::expected, std::variant, or Rust enums exist, to make that constraint explicit in the type system.
- unclad5968 1y agoYeah that makes sense. My assertion was definitely incorrect, but also not really what I was trying to describe. My argument is that they are not conceptually different. The implementation is different, in that a union occupies the same memory for either value, but whether they occupy the same memory or not, you have to check the value to determine that is an error. The compiler can force you to handle multiple return values the same way it can force you to check a variant.
- abtinf 1y agoIMHO, the actual problem with go error handling isn’t the error handling at all — it’s that multiple return values aren’t a first class construct. With proper tuple handling and Go’s approach to generics, a lot of these issues would just disappear.
- JamesSwift 1y agoThis also grinds my gears when converting multiple-return functions to returns-a-channel functions. Generics help with that now.
- kubb 1y agoTLDR: we didn't fix it for such a long time that now it's too late to fix it. We won't be fixing it, thanks! Edit: looking at the results of their H1 2024 survey, they're making a hard turn into AI, and most likely will be developing AI libraries to close the gap with Python. Don't expect language features.
- codehakase 1y agoCan't believe we're going to get GTA 6 before an agreed upon (cleaner) error handling pattern in Go.
- HippoBaro 1y agoJust to add my two cents—I’ve been writing Go professionally for about 10 years, and neither I nor any of my colleagues have had real issues with how Go handles errors. Newcomers often push back on this aspect of the language (among other things), but in my experience, that usually fades as they get more familiar with Go’s philosophy and design choices. As for the Go team’s decision process, I think it’s a good thing that the lack of consensus over a long period and many attempts can prompt them to formally define a position.
- ummonk 1y agoYeah once you've been using it long enough for the Stockholm syndrome to set in, you come to terms with the hostile parts of the language.
- janderland 1y agoI suspect a lot of us don’t have strong feelings either way and don’t find the verbosity “hostile”. No need for Stockholm syndrome if you don’t feel like a prisoner. Of course you may have been joking, in which case “haha”. xD
- Mawr 1y agoIf you say so. For me it's always been the opposite - I'm excited at the start about all the cool features, then slowly get disillusioned because of the warts.
- dangoodmanUT 1y agoThis, it’s always the new people complaining about error handling. I have many things to complain about for other languages that I’m sure are top-tier complaints too
- tines 1y agoI appreciate the argument that things can often be difficult for noobs but actually fine or better than alternatives once you get used to them. But on the other hand, people who are "used to the way things are" are often the worst people to evaluate whether changes are beneficial. It seems like the new people are the ones that should be listened to most carefully. I'm not saying the Go team was wrong in this decision, just that your heuristic isn't necessarily a good one.
- danenania 1y agoI have no problem with Go’s error handling. It’s not elegant, but it works, and that’s very much in keeping with the pragmatic spirit of Go. I’m actually kind of surprised that it’s the top complaint among Go devs. I always thought it was more something that people who don’t use Go much complain about. My personal pet issue is lack of strict null checks—and I’m similarly surprised this doesn’t get more discussion. It’s a way bigger problem in practice than error handling. It makes programs crash in production all the time, whereas error handling is basically just a question of syntax sugar. Please just give me a way to mark a field in a struct required so the compiler can eliminate nil dereference panics as a class of error. It’s opt-in like generics, so I don’t see why it would be controversial to anyone?
- CactusRocket 1y agoI have 2 problems. It's too easy to accidentally write `if err == nil` instead of `if err != nil`. I have even seen LLMs erroneously generate the first instead of the latter. And since it's such a tiny difference and the code is riddled with `if err != nil`, it's hard to catch at review time. Second, you're not forced by the language to do anything with the error at all. There are cases where `err` is used in a function that not handling the `err` return value from a specific function silently compiles. E.g. x, err := strconv.Atoi(s1) if err != nil { panic(err) } y, err := strconv.Atoi(s2) fmt.Println(x, y) I think accidentally allowing such bugs, and making them hard to spot, is a serious design flaw in the language.
- danenania 1y agoI guess those are fair criticisms in the abstract, but personally I can’t recall a single time either has caused a bug for me in practice. I also can’t ever recall seeing an LLM or autocomplete mess it up (just my personal experience—I’m sure it can happen).
- masklinn 1y ago> It’s opt-in like generics, so I don’t see why it would be controversial to anyone? It "breaks" the language in fundamental ways — much more fundamental than syntactic sugar for error handling — by making zero values and thus zero initialisation invalid. You even get this as a fun interaction with generics: func Zero[T any]() T { var v T return v }
- ziml77 1y agoThey admit it's contrived, but this isn't very convincing func printSum(a, b string) error { x, err := strconv.Atoi(a) if err != nil { return fmt.Errorf("invalid integer: %q", a) } y, err := strconv.Atoi(b) if err != nil { return fmt.Errorf("invalid integer: %q", b) } fmt.Println("result:", x + y) return nil } It's not adding anything that the Atoi function couldn't have reported. That's a perfect case for blindly passing an error up the stack.
- nasretdinov 1y agoIt does, it says which one of the two integers was incorrect
- Zambyte 1y agoWhy can't Atoi report that?
- nasretdinov 1y agoI think Atoi actually does say that, but it's just a toy example. Most often functions outside the standard library don't contain the arguments in their error values
- tsimionescu 1y ago> Going back to actual error handling code, verbosity fades into the background if errors are actually handled. Good error handling often requires additional information added to an error. For instance, a recurring comment in user surveys is about the lack of stack traces associated with an error. This could be addressed with support functions that produce and return an augmented error. In this (admittedly contrived) example, the relative amount of boilerplate is much smaller: [...] if err != nil { return fmt.Errorf("invalid integer: %q", a) } [...] It's so funny to me to call "manually supplying stack traces" as "handling an error". By the Go team's definition of handling errors, exceptions* "automatically handle errors for you". * in any language except C++, of course
- teeray 1y agoIt's funny to me when people see screenfuls of stack traces and remark how clear and useful it is. Perhaps, but do you really need all that? At what cost to your logs? I'd much rather have a one-liner wrapped error that cuts through all the framework and runtime noise. Yes, I can trace just as effectively (usually better)--the wrapping is very greppable when done well. No, in over a decade of writing Go full time, I have never cared about a runtime function or the other usual verbose garbage in my call stack.
- rwiggins 1y ago> how clear and useful it is. Perhaps, but do you really need all that? Do I need clear and useful things? Maybe not. Would I like to have them anyway? Yes. Years ago, I configured a Java project's logging framework to automatically exclude all the "uninteresting" frames in stack traces. It was beautiful. Every stack trace showed just the path taken through our application. And we could see the stack of "caused-by" exceptions, and common frames (across exceptions) were automatically cut out, too. Granted, I'm pretty sure logback's complexity is anathema to Go. But my goodness, it had some nice features... And then you just throw the stack trace in IntelliJ's "analyze stacktrace" box and you get clickable links to each line in every relevant file... I can dream. > the wrapping is very greppable when done well Yeah, that's my other problem with it. _When done well._ Every time I write an `if err != nil {}` block, I need to decide whether to return the error as is (`return err`) or decorate it with further context (`return fmt.Errorf("stuff broke: %w", err)`). (Or use `%v` if I don't want to wrap. Yet another little nuance I find myself needing to explain to junior devs over and over. And don't get me started about putting that in the `fmt` package.) So anyway, I've seen monstrosities of errors where there were 6+ "statement: statement: statement: statement: statement: final error" that felt like a dark comedy. I've also seen very high-level errors where I dearly wished for some intermediate context, but instead just had "failed to do a thing: EOF". That all being said, stack traces are really expensive. So, you end up with some "fun" optimizations: https://stackoverflow.com/questions/58696093/when-does-jvm-start-to-omit-stack-traces https://stackoverflow.com/questions/58696093/when-does-jvm-s...
- veggieroll 1y agoError handling is one of my favorite parts of Go. The haters can rip `if err != nil { return fmt.Errorf("error doing thing: %w", err) }` from my cold dead hands.
- ummonk 1y agoYou don't use gofmt?
- tom_ 1y agoThe whole point of gofmt is that you type in whatever you like and gofmt sorts it out for you. So if you're typing your code in a HN comment box, you'd surely just enter it roughly like that - though i recommend not even including the syntactically irrelevant spaces shown here. Your space bar does have a MTBF you know, and it's measured in activations... let gofmt take the strain. It can waste your screen space for you! gofmt is the good bit about working in Go. Pretty much everybody uses it, and so you can use it too. Some other languages have similar tools, but they're not as pervasive, so it's far too easy to end up in a situation where you can't use the tool because it would just make too much of a mess of the inconsistently manually-formatted stuff that's already there.
- School-Cotton 1y agorustfmt is at least as pervasive as gofmt.
- thayne 1y agoError handling is the thing I hate the most about go. And none of the serious proposals I've seen would remove your ability to continue using `if err != nil`
- veggieroll 1y agoI have yet to see a proposal that retains what I love about the status quo: conscientious error handling. The language’s status quo forces everyone to think about errors more deeply than in other languages and acknowledges that the error case is as critical and worthy of the programmer’s attention.
- hackingonempty 1y agoGenerators and Goroutines have keywords/syntax in Golang but now they don't want to pile on more to handle errors. They could have had one single bit of syntactic sugar, "do notation", to handle all three and more if they had considered it from the beginning but it seems too late if the language designers are even aware of it. TFA says "If you’re wondering if your particular error handling idea was previously considered, read this document!" but that document references languages with ad-hoc solutions (C++, Rust, Swift) and does not reference languages like Haskell, Scala, or OCaml which have the same generic solution known as do-notation, for-comprehensions, and monadic-let respectively. For example instead of func printSum(a, b string) error { x, err := strconv.Atoi(a) if err != nil { return err } y, err := strconv.Atoi(b) if err != nil { return err } fmt.Println("result:", x + y) return nil } they could have something like this: func printSum(a, b string) result[error, unit] { return for { x <- strconv.Atoi(a) y <- strconv.Atoi(b) } yield fmt.Println("result:", x + y) } which desugars to: func printSum(a, b string) result[error, unit] { return strconv.Atoi(a).flatMap(func(x string) result[error, unit] { return strconv.Atoi(b).map(func(y string) unit { return fmt.Println("result:", x + y) } } } and unlike ad-hoc solutions this one bit of syntax sugar, where for comprehensions become invocations of map, flatMap, and filter would handle errors, goroutines, channels, generators, lists, loops, and more, because monads are pervasive: https://philipnilsson.github.io/Badness10k/escaping-hell-with-monads/ https://philipnilsson.github.io/Badness10k/escaping-hell-wit...
- VirusNewbie 1y agoI absolutely agree with this, and would be better than all of the other proposals. Did anyone propose this in one of the many error handling proposals?
- MeetingsBrowser 1y agoyes
- tayo42 1y agoI don't think in real code you generally want to return "err" directly, but add some kind of context to made debugging easier. Its the same problem Rusts `?` has. How do you do that with this suggestion?
- deleted 1y ago[deleted]
- bccdee 1y agoHere's a non-syntactic suggestion. Could we just patch gofmt to permit this: if err != nil { return nil, err; } as a well-formatted line of go? Make it a special case somehow. My only big problem with if err != nil is that it eats up 3 lines minimum. If we could squish it down to 1, I'd be much more content.
- verdverm 1y agoWhat if I wrap the error? Should that be squashed to one line? What is the heuristic?
- bccdee 1y agoSure, why not? Let the programmer decide if they want one line or three lines; the tool can permit both. Gofmt is line-length-agnostic—breaking up long lines is already considered to be the programmer's responsibility.
- verdverm 1y agogo fmt already changes one-liner if statements to be multi-line you are proposing changing this, making code look different based on differences of opinions between developers go fmt is actually one of the top rated features of Go, it makes everyone's code look the same, everyone has nitpicks about it, yet by and large it is one of the most loved things about Go. Breaking this is even less likely than changing error handling
- bccdee 1y agoThe code already looks different based on different developers' opinions. Gofmt already allows this: fmt.Printf("%s %s %s %s\n", arg1, arg2, arg3, arg4) and this fmt.Printf("%s %s %s %s\n", arg1, arg2, arg3, arg4) and this fmt.Printf( "%s %s %s %s\n", arg1, arg2, arg3, arg4, ) and will not alter any of the above. All I want is similar ambiguity around one-line `if` statements. That's not so crazy.
- 1y ago
- nilirl 1y agoError handling is some of the least fun parts of writing code. In all languages. But in any case, why so much fear of being wrong? > we have fine-grained control over the language version via go.mod files and file-specific directives And that may be the real truth of it: Error handling in Go just isn't ... that much of a problem to force action?
- scoodah 1y ago> And that may be the real truth of it: Error handling in Go just isn't ... that much of a problem to force action? I you are right that this is the truth of it. Error handling just isn’t that big a problem. 13% reported it on the survey cited. That doesn’t seem that significant. And honestly, after writing Go, I barely notice error handling as I’m writing/reading code anyway. If anything I appreciate it a bit more than exceptions. Always something that can be complained about. But it doesn’t mean every complaint is a huge deal.
- dlock17 1y agoThis is also my feeling. And I wouldn't even have minded the ? syntax. It seems that now that Ian's left the rest of the Go team is just being honest about what they are willing to spend their time on. And I'm more than fine with that, because look at this comment section. You can't please everybody.
- arccy 1y agoconsidering the recent post [1] on system correctness in amazon quoting "In 2014, Yuan et al. found that 92% of catastrophic failures in tested distributed systems were triggered by incorrect handling of nonfatal errors." perhaps it's a good thing that error handling is so explicit, and treated as a regular code path. [1]: https://news.ycombinator.com/item?id=44135638 https://news.ycombinator.com/item?id=44135638
- honkycat 1y agoawesome I love noisy boilerplate in my code, it isn't annoying at all
- deleted 1y ago[deleted]
- jamamp 1y agoI like Go's explicit error handling. In my mind, a function can always succeed (no error), or either succeed or fail. A function that always succeeds is straightforward. If a function fails, then you need to handle its failure, because the outer layer of code can not proceed with failures. This is where languages diverge. Many languages use exceptions to throw the error until someone explicitly catches it and you have a stack trace of sorts. This might tell you where the error was thrown but doesn't provide a lot of helpful insight all of the time. In Go, I like how I can have some options that I always must choose from when writing code: 1. Ignore the error and proceed onward (`foo, _ := doSomething()`) 2. Handle the error by ending early, but provide no meaningful information (`return nil, err`) 3. Handle the error by returning early with helpful context (return a general wrapped error) 4. Handle the error by interpreting the error we received and branching differently on it. Perhaps our database couldn't find a row to alter, so our service layer must return a not found error which gets reflected in our API as a 404. Perhaps our idempotent deletion function encountered a not found error, and interprets that as a success. In Go 2, or another language, I think the only changes I'd like to see are a `Result<Value, Failure>` type as opposed to nillable tuples (a la Rust/Swift), along with better-typed and enumerated error types as opposed to always using `error` directly to help with error type discoverability and enumeration. This would fit well for Go 2 (or a new language) because adding Result types on top of Go 1's entrenched idiomatic tuple returns adds multiple ways to do the same thing, which creates confusion and division on Go 1 code.
- barrkel 1y agoMy experience with errors is that error handling policy should be delegated to the caller. Low level parts of the stack shouldn't be handling errors; they generally don't know what to do. A policy of handling errors usually ends up turning into a policy of wrapping errors and returning them up the stack instead. A lot of busywork.
- XorNot 1y agoAt this point I make all my functions return error even if they don't need it. You're usually one change away from discovering they actually do.
- melodyogonna 1y agoGo's error handling fade away after a month of consistent use, I would not risk backwards compatibility over this. In fact, I like the explicit error handling.
- thayne 1y agoThe proposals are not backwards incompatible. And just because you get used to something doesn't mean it is good. And FWIW, my hatred of go error handling has not diminished with increased usage.
- sedatk 1y ago> I like the explicit error handling You mean "verbose error handling". All other proposals are also explicit, just not as verbose.
- TZubiri 1y agoLove it, focus on building with what we have. Resist enshittification, the greatest advantage in foundational software is sometimes saying no to new features.
- d3ckard 1y agoFrom the Elixir's developer perspective, this is insane. The issue is solved in Erlang / Elixir by functions commonly returning {:ok, result} or {:error, description_or_struct} tuples. This, together with Elixir's `with` statement allows to group error handling at the bottom, which makes for much nicer readability. Go could just add an equivalent of `with` clause, which would basically continue with functions as long as error is nil and have an error handling clause at the bottom.
- throwawa14223 1y agoGo's multiple return is in itself insane from my perspective. You cannot 'do' anything with a function that has multiple return types except assign them to a variable.
- masklinn 1y agoThe saddest part is that Go's designers decided to use MRV but pretty much just as bad tuples: as far as I can tell the only thing Go uses MRV for which tuple wouldn't be better as is post-updating named return values, and you could probably just update those via the container. Common Lisp actually does cool things (if a bit niche) things with MRVs, they're side-channels through which you can obtain additional information if you need it e.g. every common lisp rounding functions returns rounded value... and the remainder as an extra value. So if you call (let ((v (round 5 2))) (format t "~D" v)) you get 2, but if you (multiple-value-bind (q r) (round 5 2) (format t "~D ~D" q r)) you get 2 and 1.
- bravesoul2 1y agoYou can at least in Go do this: r, err := f() r := f() _, err := f()
- masklinn 1y agoNo, you can not do the second one. The other two are completely routine and will work just fine with lists in JS or tuples in Python or Rust (barring a few syntactic alterations).
- renewiltord 1y agoI am very entertained by this. The Golang community bikeshedded their way into the status quo. Hahaha, I have to say that's a pretty good move by the steering org. Punishes bikeshedding.
- stackedinserter 1y agoIDE's could help and just hide standard `if err != nil return fmt.Errorf("sh: %w", err)` blocks for us, or show them in some distinct way, like question mark after the statement.
- Mond_ 1y agoI really don't like how this article claims that the primary issue with Go's error handling is that the syntax is too verbose. I don't really care about that. How about: - Errors can be dropped silently or accidentally ignored - function call results cannot be stored or passed around easily due to not being values - errors.Is being necessary and the whole thing with 'nested' errors being a strange runtime thing that interacts poorly with the type system - switching on errors being hard - usage of sentinel values in the standard library - poor interactions with generics making packages such as errgroup necessary Did I miss anything?
- GiorgioG 1y agoJust remember it took FOREVER for Go to support some form of generics. Go evolution happens at a glacial pace. That's a feature, not a bug....to many.
- neild 1y ago> I really don't like how this article claims that the primary issue with Go's error handling is that the syntax is too verbose. I don't believe this claim is made anywhere. We've decided that we are not going to make any further attempts to change the syntax of error handling in the foreseeable future. That frees up attention to consider other issues (with errors or otherwise).
- pas 1y agowriting a small book on the topic and somehow missing it is the point, not that technically the text is claiming it, the subtext is doing it.
- VirusNewbie 1y agoAgreed, 100%. We're both Googlers here and this is so disappointing to be let down again by the Go team.
- closeparen 1y ago90% of working professionally in Go is contriving test cases to achieve statement coverage over each error return branch, something no one would ever do in a language with exceptions.
- eximius 1y agoAh, shame. `foo := someFallibleMethod()?` would have been nice for when you don't want to handle/wrap the error. I'm not super strongly against the constant error checking - I actually think it's good for code health to accept it as inherent complexity - but I do think some minor ergonomics would have been nice.
- pikzel 1y agoThey still haven't solved shadowing. a, err := foo() b, err := bar() if err != nil { // oops, forgot to handle foo()'s err } This is the illusion of safe error handling.
- AnimalMuppet 1y agoI would be astonished if there isn't an automated tool to check for that at the push of a button. I would be mildly surprised if there isn't a compiler flag to check for it.
- arp242 1y agoNot a compiler check, but staticcheck is widely used: % staticcheck test.go test.go:7:2: this value of err is never used (SA4006)
- dmitshur 1y agoYeah, as one data point, https://staticcheck.dev/docs/checks/#SA4006 https://staticcheck.dev/docs/checks/#SA4006 has existed since 2017.
- masklinn 1y agoThere very much is not. There is a compiler error you can’t disable if a variable is completely unused and that is it.
- _benton 1y agoIt's fairly obvious when writing Go that `err` is being shadowed and needs to be checked after each expression. You should be wrapping them anyways!
- catlifeonmars 1y agoI’m surprised I don’t see this mentioned more. This is spooky action at a distance at its worst. And it’s not even limited to error handling. Any multi value assignment works like this.
- agumonkey 1y agomakes you miss the `or die` idiom :)
- anttiharju 1y agoI was actually bit scared, so read through the whole post and am happy with the conclusion. Go is very readable in my experience. I'd like to keep it that way.
- cherryteastain 1y agoAll they have to do is to expand generics to support generic methods so we can have monadic operations like in C++'s std::expected or Rust's Result, like func (r Result[T, E]) AndThen[OtherT any](func(T) Result[OtherT, E]) Result[OtherT, E] { ... } which would enable error handling like sum := 0 parseAndAdd := func(s string) (func(string)Result[int, error]) { /* returns func which parses and adds to sum */ } return parseAndAdd(a)().AndThen(parseAndAdd(b)) There's a reason why every other language is converging to that sort of functional setup, as it opens up possibilities such as try-transform generics for ranges.
- tslocum 1y agoSeems strange that Rust's "?" gets a mention syntax-wise, but nothing is said about sum types coming to Go. Go's verbose error handling and lack of sum types are my only gripes with the language. It would be nice to see both addressed using Rust's Result type as a model.
- reader_1000 1y ago> For instance, a recurring comment in user surveys is about the lack of stack traces associated with an error. This could be addressed with support functions that produce and return an augmented error. Languages with stack traces gives this to you for free, in Go, you need to implement it every time. OK, you may be disciplined developer where you always augment the error with the details but not all the team members have the same discipline. Also the best thing about stack traces is that it gives you the path to the error. If the error is happened in a method that is called from multiple places, with stack traces, you immediately know the call path. I worked as a sysadmin/SRE style for many years and I had to solve many problems, so I have plenty of experience in troubleshooting and problem solving. When I worked with stack traces, solving easy problems was taking only 1-2 minutes because the problems were obvious, but with Go, even easy problems takes more time because some people just don't augment the errors and use same error messages which makes it a detective work to solve it.
- Pxtl 1y agoI've never used Go but having used other languages with exception-based error handling, I get why Go decided to go in a different direction... but reading this over... Okay, so surely some syntactic sugar could make it more pleasant than the if (err != nil) { return nil, err } repeated boilerplate. Like, if that return is a tagged union you could do some kind of pattern matching? ... oh, Go doesn't have sum-types. Or pattern matching. Could you at least do some kind of generic error handler so I can call y := Handle(MyFuncThatCanReturnError(x)) ? ... Okay, GoLang does not have tuples. Multiple returns must be handled separately. Okay could I write some kind of higher-order function that handles it in a generic way? Like y := InvokeWithErrorHandler(MyFuncThatCanReturnError, x) ? No? That's not an option either? ... why do you all do this to yourselves?
- tail_exchange 1y agoThis doesn't actually makes the process simpler. Error handling in Go is not just writing "if err != nil { return nil, err }" for every line. You are supposed to enrich the error to add more context to it. For example: result, err := addTwoNumbers(a, b) if err != nil { return fmt.Errorf("addTwoNumbers(%d, %d) = %v", a, b, err) } This way you can enrich the error message and say what was passed to the function. If you try to abstract this logic with a "Handle" function, you'll just create a mess. You'll save yourself the time of writing an IF statement, but you'll need a bunch of arguments that will just make it harder to use. Not to mention, those helper functions don't account for cases where you don't just want to bubble up an error. What if you want to do more things, like log, emit metrics, clean up resources, and so on? How do you deal with that with the "Handle()" function?
- Pxtl 1y agoObviously I'm being terse for argument. You can easily imagine InvokeWithErrorLogger(fn, fnparam, log) or InvokeWithErrorAnnotator(fn, fnparam, annotatorFn) Or any other common error-handling pattern.
- tail_exchange 1y ago
- Bratmon 1y agoWatching go people complaining about how other languages encourage bubbling errors up is always hilarious to me because there is literally nothing you can do with errors in go except bubble them up, log them, or swallow them. Even the article considers "handling" an error to be synonymous with "Adding more text and bubbling it up"!
- gwd 1y agoI mean, yeah, most of the time what you do is add more text and bubble up. But: 1. The very fact that adding more text isn't really any more verbose than not encourages you to add more text, making errors more informative. 2. A non-negligible amount of times you do something else: carry on, or do something specific based on what kind of error it was. For instance, ignore an error if it's in a certain class; or create the file if it didn't exist; and so on. Forcing the error handling doesn't seem to me that different than forcing you to explicitly cast between (say) int and int64. Part of me is annoyed with that too, but then I have PTSD flashbacks from 20 years of C programming and appreciate it.
- DangitBobby 1y ago> making errors more informative. It makes them almost as informative as languages with stack traces! Imagine if Go had a syntax like python's raise Exception("bad thing happened") from err I'd love that.
- tail_exchange 1y ago> there is literally nothing you can do with errors in go except bubble them up, log them, or swallow them You can also add additional context to the error before bubbling it up. But yes, that part of the point. Instead of bubbling them up, the programmer should instead reflect on whether it is better than just log and proceed, or completely swallow them. This is what error handling is about.
- Mawr 1y agoI assume you mean languages with exceptions. You can't bubble up an exception, it's done automatically. That's a very important distinction. You can't make the decision to bubble up or not, because you do not have the required information - you don't know whether an exception can be thrown or not at any point. Therefore, you can't say you're making a decision at all. Explicit error allows you to be able to make the decision.
- latchkey 1y agoGauntlet, the CoffeeScript of golang, seems to have an interesting approach: https://gauntletlang.gitbook.io/docs/advanced-features/try-statements https://gauntletlang.gitbook.io/docs/advanced-features/try-s...
- klabb3 1y agoI love Go, but this is almost farcically hilarious: > The goal of the proposal process is to reach general consensus about the outcome in a timely manner. If proposal review cannot identify a general consensus in the discussion of the issue on the issue tracker, the usual result is that the proposal is declined. > None of the error handling proposals reached anything close to a consensus, so they were all declined. > Should we proceed at all? We think not. The disconnect here is of course that everyone has opinions and Google being design-by-committee can’t make progress on user-visible changes. Leaving the verbose error handling is not the end of the world, but there’s something here missing in the process. Don’t get me wrong, I love inaction as a default decision, but sometimes a decision is better than nothing. It reminds me of a groups when you can’t decide what to have for dinner – the best course of action isn’t to not eat at all, it’s to accept that everyone won’t be happy all the time, and take ownership of that unhappiness, if necessary, during the brief period of time when some people are upset. I doubt that the best proposals are so horrible for some people that they’d hold a grudge and leave Go. IME these stylistic preferences are as easily abandoned as they are acquired. To put another way: imagine if gofmt was launched today. It would be absolutely impossible to release through a consensus based process. Just tabs vs spaces would be 100 pages on the issue tracker of people willing to die on that hill. Yet, how many people complain about gofmt now that it’s already there? Even the biggest bike shedders enjoy it.
- VirusNewbie 1y agoIt's true that Google is "design by committee" and consensus driven, but the Go team has been particularly obtuse about things, seemingly not understanding which opinions are valid and which are confused.
- zaptheimpaler 1y agoYeah this bugs me about the decision process too, but Go places more importance on backwards compatibility and stability than most other languages so it does align with their values. I'm not the biggest fan of Go but its nice having a language around that favors simplicity and stability.
- derefr 1y agoTo take this analysis another level deeper: what has happened here is a classic example of bikeshedding — and, worse, fostering bikeshedding. Everyone feels equipped to have an opinion about "what should be the syntax for an obvious bit of semantics." There's no expertise required to form such an opinion. And so there are as many opinions on offer as there are Go developers to give them. Limit input on the subject to just e.g. the people capable of implementing the feature into the Go compiler, though, and a consensus would be reached quickly. Unlike drive-by opinion-havers, the language maintainers — people who have to actually continue to work with one-another (i.e. negotiate in an indefinite iterated prisoner's dilemma about how other language minutiae will work), are much more willing to give ground "this time" to just move on and get it working. (Tangent: this "giving ground to get ground later" is commonly called "horse trading", but IMHO that paints it in a too-negative light. Horse trading is often the only reason anything gets done at all!)
- mparnisari 1y agoI have zero complaints about Go's error handling and I'm happy with the decision!
- shermantanktop 1y ago"Not adding extra syntax is in line with one of Go’s design rules: do not provide multiple ways of doing the same thing" And so any change to any existing functionality is a breaking change that invalidates all code which uses that functionality? That design rule smells like hubris on the part of Go's designers. It only works if all future changes are extensions and never amendments.
- karel-3d 1y agoHm, I would agree with this 2 years ago; but now I see how great both iterators and generics were despite my initial personal objections, so I am thinking we should give some less verbose error handling a chance. But alas
- bravesoul2 1y agoSlowly reinventing exceptions seems to go against the spirit of Go. That is what you read is what you get. Haskell solves this with the do notation, but the price is understanding monads. Go also aims to be easy to understand.
- thayne 1y agoThe proposals aren't reinventing exceptions. They are just making more ergonomic syntax for doing the same thing go error handling does today.
- bravesoul2 1y agoYou can argue that is what an exception is. A more ergonomic way to deal with errors that handles propagation for you.
- thayne 1y agoThat doesn't mean that any ergonomic way to handle errors is necessarily an exception system. Rust's ? operator is more ergonomic than go's error handling, but it is definitely not an exception system.
- JyB 1y agoThis is such a great move. Faith restored in the language after the generics debacle.
- agluszak 1y ago> generics debacle Why debacle?
- sedatk 1y agoI'm so happy that Rust sorted this out way early in its lifetime. Error handling is so nice there.
- tick_tock_tick 1y agoRust is basically someone looking at ML languages and thinking what if we did that but just worse in every way.
- Neku42 1y agoEven if the decision to close the door on this sucks I think they are correct - this is not a syntax problem. Adding sugar will not fix fundamental issues w/ Go's error handling. They need to add/fix like 5-6 different parts of the language to even begin addressing this in a meaningful way.
- ivanjermakov 1y agoNo one here mentioned Zig approach there, so I'll share: https://ziglang.org/documentation/master/#try https://ziglang.org/documentation/master/#try Zig has try syntax that expands to `expr catch |e| return e`, neatly solving a common use case of returning an error to the caller.
- joaohaas 1y agoZig 'error types' are a sum type, while Go ones are just values. And even then this is just the same as the '?' operator Rust uses, which is mentioned in the post.
- tubthumper8 1y agoThe "Error Return Trace" described in the next section down also seems like an interesting alternative to a stack trace, possibly solving the same problem with less noise. How well does it work in practice?
- kristoff_it 1y agoIt works really, really well, in part because it's also capable of tracking where an error is turned into another. And the error return trace ends where the stack trace begins (when an error is turned into a panic) so you don't even have to know what an error trace is, because it just makes sense intuitively.
- dcow 1y agoGo’s philosophy is the problem: sometimes you need a few ways to do the same thing. And that’s okay. Sometimes the flow you’re trying to express in code just needs the error to go up and get handled at the top. Sometimes you want to act on it. Right now all you can do is act on it. So all the times you don’t need to act on it have to suffer? I call profuse bullshit. There is 100% a way to add terse compiler-enforced error handling (for the love of all things holy if nothing at all changed with the syntax at least there should be consensus that it’s a serious problem that the compiler can’t tell you “oops you forgot to handle that error”) to be added in a way that doesn't bifurcate API surfaces. You just have to do it even in the face of dissent. You have to compromise on your values for the good of the language. What is the damn problem with ? literally expanding to `if err != nil { \n return err \n }`? Just take small steps that improve everyone’s life. If you look for excuses not to improve error handling you’ll find them. Sadly that appears to be what has happened here. The entire language suffers because a vocal minority are sadists. Is it time for me to come back to Go? I think not.
- lspears 1y agoGo’s restraint in adding new language features is a real gift to its users. In contrast, Swift feels like a moving target: even on a Mac Studio I’ll occasionally fail to compile a simple project. The expanding keyword list and nonstop churn make Swift harder to learn—and even harder to keep up with.
- parentheses 1y agoThe fundamental thing that try/catch and similar language structures give us is an error _boundary_. I feel that not having one is a weakness of the language. The nesting and syntax all serve the purpose of handling errors neatly. I think it works very well and Go has unsolved the problem. I am not saying that the mechanism is perfect but it is more useful if we have it than not. IMO it's only weakness is that you never know if a new exception type is thrown by a nested function. This is a weakness for which we really don't have a solid solution - Java tried this with checked exceptions. Go not using such a paradigm to me is bonkers. Practically every language has such a construct and how we use it best is pretty much convention these days.
- keyle 1y agoIt saddens me that the conclusion is "it's been like this for this long now" and "no one could ever agree to something" leads to this amount of verbosity. Any of these keywords approach, `try`, `check`, or `?` would have been a good addition, if they kept the opportunity to also handle it verbosely. The argument that LLM now auto-completes code faster than ever is an interesting one, but I'm baffled by such an experienced team making this an argument, since code is read so many more times than it is written; they clearly identify the issue of the visual complexity while hand-waving the problem that it's not an issue since LLM are present to write it - it completely disregards the fact that the code is read many more times that it is written. Visual complexity and visual rhythms are important factors in a programming language design, I feel. Go is excruciatingly annoying to read, compared to Dart, C, or any cleaner language. Ultimately, it's just one of those "meh, too hard, won't do" solution to the problem. They'll write another one of those posts in 5 years and continue on. Clearly these people are not there to solve user problems. Hiding behind a community for decision making is weak. Maybe they should write some real world applications themselves, which involves having these error checks every 2nd lines. At this point I wouldn't be upset if someone forked Go, called it Go++ and fixed the silly parts.
- catlifeonmars 1y agoI’m somewhat surprised this was a topic that was deemed worthy of a blog post. It seems quite out of character with other blog posts on the Go blog which are usually about introducing a new feature. Sure, Go’s relatively verbose error handling has long been a source of controversy, but was it worth publishing a blog post just to say, effectively: “please shut up”?
- peterashford 1y agoI like Go. I use it at work and I find it pretty pragmatic. But I can't stand the verbosity of the error handling. It drives me nuts. I also can't stand the level of rationalising that goes on when anyone dares to point out that Go's error handling is (obviously) verbose. The community has a pigheaded attitude towards criticism. It also grinds my gears, because I really like that Go is in most other ways, simple and low on boilerplate. It's not unusual to see functions that are 50% error handling where the error handling actually DOES NOTHING. That's just insane.
- skissane 1y agoAnother way of potentially addressing this problem: add some kind of macro facility to Go – maybe take inspiration from Rust This could be used to solve both "syntactic support for error handling", and also various other common complaints (such as lack of first class enums), without "polluting" the core language – they'd be optional packages which nobody would have to use if they don't want to Of course, if one of these optional packages ever became truly prevalent, you could promote it to the standard library... but that would involve far less bikeshedding, because it would be about making the de facto standard de jure... and arguably, letting people vote with their feet is a much more reliable way of establishing consensus than any online discussion could ever be
- MathMonkeyMan 1y agoOne of Rob Pike's talks convinced me that the tendency to add features from other languages causes languages to all resemble each other. It's not a bad thing, but it's something to note. Consider the alternative: What if we had different languages for different tasks, new languages appearing from time to time, rather than accreting features onto existing general purpose languages every few years? He also made the point that if you have two ways of coding something, then you have to choose every time. I've noticed that people disagree about which way is best. If there were only one way, then all of the same problems would be solved with the same amount of effort, but without any of the disagreement or personal deliberation. Maybe Go should have exceptions beyond what panic/recover became, or maybe there should be a "?" operator, or maybe there should be a "check" expression, or some other new syntax. Or maybe Go code should be filled with "if" statements that just return the error if it's not nil. I've worked with a fair amount of Go code, but not enough that I am too bothered by which pattern is chosen. On the other hand, if you spend more than a few weeks full time reading and editing Go code, you could easily learn a lot of syntax without issue. If you spend most of your career writing in a language, then you become familiar with the historical vogues that surrounded the addition of new language features and popular libraries. There's something to be said for freezing the core language.
- catlifeonmars 1y agoSmall nitpick: panic/recover and error handling are orthogonal. Exceptions != errors.
- cyberax 1y agoSigh. They failed. Dudes, error handling is THE worst part of Go. All of it. And not just the lack of the "?" operator. It's also the lack of stacktraces, the footguns with nils-that-are-not-nil, problems with wrapping, the leakage of internal error messages to users (without i18n). Literally everything. And you're just shutting down even _discussions_ of this?
- never_inline 1y ago> When debugging error handling code, being able to quickly add a println or have a dedicated line or source location for setting a breakpoint in a debugger is helpful. On the flip side, you can't have exception breakpoints in Go.
- nvlled 1y ago> To be more precise, we should stop trying to solve the syntactic problem Fixing the problem purely from a syntactic perspective avoids any unexpected semantic changes that could lead to irreconcilable disagreements, as clearly demonstrated by the infamous try proposal. Very simple syntactical changes that maps clearly to the original error handling has the advantage of being trivial to implement while also avoids having the developers needing to learn something new.
- codr7 1y ago[flagged]
- tmaly 1y agoI like that it we are forced to deal with the error. It seems to make the code more predictable in some sense. But I do loath the littered if err != nil { return err } maybe a better autocomplete in the IDE/editor is a good compromise.
- rerdavies 1y agoIt's a shame they haven't polled people who refuse to use the language. No exceptions? Maybe it's time to revisit that decision.
- eviks 1y ago> After so many years of trying, with three > We didn’t have a better solution at that time and didn’t pursue syntax changes for error handling for several years. 3 is small, and it seems like there were more years of not trying at all. And the example of one proposal is telling. It had a major control flow issue, so got rejected, but then there is a recent proposal fixing those issues, and the post just goes on without further elaboration? > Unfortunately, as with the other error handling ideas, this new proposal was also quickly overrun with comments and many suggestions for minor tweaks, often based on individual preferences. How is this unfortunate? If the tweaks are good, update the proposal using them, so that's very fortunate? If they aren't, explain why there rejected? Or do you only expect a binary yes/no on the proposal as originally published? I mean, no wonder with such an approach the only way forward is to give up.