15 ms·
New in Go 1.20: wrapping multiple errors
- donatj 4y agoGiven the now two interfaces, Unwrap() error and Unwrap() []error I really wish they had just done only the latter since the beginning. Continuing to have and support the prior feels like a mistake somewhat permanently baked into the language. I know it is easy to armchair second guess but one of the very first things I tried when they added wrapping a couple versions ago was wrapping multiple errors. I am reasonably certain the majority of the pre-native library error wrapping packages supported multiple errors as well. The desire seems reasonably obvious.
- Rapzid 4y agoSomething about needing to use fmt.Errorf to JOIN errors if you want custom string formatting rubs me the wrong way. I had to read that section twice because it completely went over my head it acting as a join.. So unexpected for fmt to be doing error biz like that.
- leetrout 4y agoEspecially given the current landscape of log handling as the author points out. I am all in on structured logging most of the time and I don't want to have to deal with a newline causing multiple records in my log aggregation.
- Rapzid 4y agoIt's also not true the interface for Unwrap() doesn't exist; behold https://cs.opensource.google/go/go/+/refs/tags/go1.19.4:src/errors/wrap.go;l=14 https://cs.opensource.google/go/go/+/refs/tags/go1.19.4:src/... ... Yeah, it's not exported but...
- lzap 4y agoIn the blogpost I specifically wrote "There is no (named) interface in the standard library..." because I was aware of the function you point out. Rather than unexported interface, I would probably call that an "anonymous interface". Anyway, now that I read that, I should probably skip this fact and just keep the example interface. It is not uncommon practice in Go to make "copies" of interfaces to avoid extra dependency (or cyclic dependency).
- Rapzid 4y agoSorry, that shot right past me. The article sounded, to me anyway, impressed the interface didn't exist. Seeing the cast/check against the anonymous interface left me unimpressed haha. > It is not uncommon practice in Go to make "copies" of interfaces to avoid extra dependency (or cyclic dependency). I hadn't really noticed but my exposure to the source is spotty. See what they are doing there and can imagine why, it just irks me. There are now implicit, "standard" shapes for Error that don't have named, exported interfaces and presumably anyone wanting to write code around both Unwrap shapes will need to reach for the same techniques to suss out what they are dealing with..
- morelisp 4y ago> needing to use fmt.Errorf to JOIN errors if you want custom string formatting You don't need to, you can implement Unwrap yourself and format the error however you want, just like singular errors today. > unexpected for fmt to be doing error biz like that. IIRC, this has to do with avoid circular package dependencies. fmt can depend on errors (and quite a lot of other stuff) but errors can't depend on fmt, so either a) errors needs to implement its own format string processing, b) a wholly new errfmt package is introduced, c) fmt.Errorf.
- Rapzid 4y ago> You don't need to, you can implement Unwrap yourself and format the error however you want, just like singular errors today. Sure, but when discussing the language stdlib design being able to reimplement myself isn't particularly germane. It's what is provided that's being criticized. > IIRC, this has to do with avoid circular package.. The journey to the bad design is interesting, but here we are haha. IMHO it's weird (poor design) to have fmt as the place to join errors if we want to customize the string. The article tries to make the case that errors ARE just strings, but I don't buy what it's selling. The type checks in Is and interface casting in Unwrap are my counter arguments.
- p-e-w 4y agoYears and years of discussions about Go's poor and verbose error handling, with multiple sensible proposals being rejected, and this is the improvement that finally makes it into a release? What Go demonstrates above all else is how successful a poorly designed language can be if it has a great compiler, an amazing standard library, and high-quality official tooling. Many "features" of Go are borderline insane (date formatting, lack of enums, implicit interfaces, ...) and Go repeats design mistakes that were recognized as mistakes decades ago (nil pointers), but all of that is happily overlooked in practice because huge codebases compile in three seconds, you don't have to argue about which formatter configuration to use, and everything from TLS to CSV is rolled into std without ever having to import a third-party repository.
- tejinderss 4y ago> everything from TLS to CSV is rolled into std without ever having to import a third-party repository And yet the std library is missing some basic data structures like Set.
- p-e-w 4y agoBecause they can't be properly implemented without generics, and generics were only shoehorned into Go a decade after its initial release.
- kasey_junk 4y agoThe go language has had generics since inception, just not user defined ones. If they wanted a set data structure they could have had it like they do maps and slices.
- XorNot 4y agoSet is just a Map though where you don't care about the values. var m[string]struct{} implements this for you. What you're really missing is the usual suite of helper methods which make sets ergonomic - and for that you need proper generics.
- candiddevmike 4y agoI still don't see a benefit with this over custom error types. Having a huge switch statement to determine the HTTP response code seems really inefficient vs just doing errors.As and getting the response code directly.
- sidlls 4y agoIt is not efficient, except at that one point in time you write the code. This is `errors.As`: https://cs.opensource.google/go/go/+/refs/tags/go1.19.4:src/errors/wrap.go;l=78 https://cs.opensource.google/go/go/+/refs/tags/go1.19.4:src/.... It uses reflection and type assertions and itself contains error checking (e.g. to validate that the arguments are actually error interfaces). It looks efficient in your code because the call is compact, but this is not even close to efficient, and especially not as efficient as a switch statement.
- hellcow 4y agoIt’s very useful when multiple errors happen concurrently, like collecting errors from separate goroutines after they all finish.
- lzap 4y agoGreat example, should have known this one.
- lzap 4y agoAs I said in the article, the example is simplified. As you point out, incorporating the HTTP code into the error and using errors.As is much better way of doing that: "Obviously, the common HTTP status codes could easily be a new error type (based on int type) so the actual code could be easily extracted via errors.As, but I want to keep the example simple."
- knorker 4y agoWhen comparing how Go changes with how C++ changes, one gets renewed appreciation for how good of a job the C++ designers are doing. The more Go evolves, the more clear it gets that it has a very poorly designed foundation. I say that as someone who's coded and reviewed a lot of Go code. Maybe they should not have skipped 40 years of language theory when first creating it. It wasn't obvious in the beginning, but now...
- vsnf 4y ago> It wasn't obvious in the beginning, but now... Was it not obvious at the beginning that this was a bad idea? What was the state of programming languages where consciously tossing out progress was considered not on, its face, insane?
- knorker 4y agoDepends where you were going. What I mean is that you can start a small language with shaky fundamentals, but when you try to grow it to take over it becomes a problem. But yes, if the goal was to grow then it's a bad place to start from.
- pjmlp 4y agoIn a sense this is a tradition that the Go authors already followed once when designing C. "Although we entertained occasional thoughts about implementing one of the major languages of the time like Fortran, PL/I, or Algol 68, such a project seemed hopelessly large for our resources: much simpler and smaller tools were called for. All these languages influenced our work, but it was more fun to do things on our own. " -- https://www.bell-labs.com/usr/dmr/www/chist.html https://www.bell-labs.com/usr/dmr/www/chist.html
- twsted 4y ago> When comparing how Go changes with how C++ changes, one gets renewed appreciation for how good of a job the C++ designers are doing. We must live in a different world...
- 4y ago
- imiric 4y agoI guess it's become trendy to hate on Go in this forum, so I'll offer a counterpoint. Being a relative newcomer to the language, transitioning from Python circa 2016, I've found it a joy to use. The simplicity of the spec, the true "one way to do it" philosophy, the way it forces you to simplify and avoid cleverness (yes, sometimes at the expense of verbosity, which only makes things clearer, and rarely tedious), the great crossplatform support, stdlib, and tooling around it, and many more features, have made it my favorite language. Yes, there are still some warts and odd design decisions, but those are far outnumbered by the good things about it. Most of the issues are related to Go's team unwavering dedication to backwards compatibility, which is respectable. The fact we got generics in v1 is incredible. I can't wait for what v2 will bring, without the shackles of backwards compatibility. This errors feature in 1.20 is neat, but I'm much more excited for context cancellation reasons[1], which will hopefully be released soon as well. That should greatly simplify debugging, and avoid the common generic "context canceled" errors. [1]: https://github.com/golang/go/issues/46273 https://github.com/golang/go/issues/46273
- fideloper 4y agoLooks like that specific issue / change wasn't accepted, but this[1] alternative will be. That seems like a great change to me. [1]: https://github.com/golang/go/issues/51365 https://github.com/golang/go/issues/51365
- vlunkr 4y agoThe conversation around Go on HN is as broken as a political discussion on Facebook. It’s pathetic.
- kaba0 4y agoI think “go haters” bring up plenty of valid points, unlike.. unfortunately any discussion on facebook.
- vlunkr 4y agoThe post is about a new feature related to errors, the top comment is the same old complaint about verbose error handling, which is only tangentially related. I wouldn’t consider that quality discussion.
- nvarsj 4y agoI find it ironic that golang refuses to introduce exceptions, but instead is slowly turning errors into a crappy substitute. I feel like a modern language should do either two things with errors: exceptions, or a result monad. Since the language is GC'd and doesn't have language support to make a result type practical, it seems like exceptions are a no brainer.
- kajaktum 4y ago>Since the language is GC'd and doesn't have language support to make a result type practical, it seems like exceptions are a no brainer. Elaborate? What prevents Go from introducing result monad aside from the syntax?
- nvarsj 4y agoI'm sure it could introduce something _like_ a result monad, but with the associated very clunky/verbose syntax in golang which reduces to conditionals and lots of type casts. I guess this is sort of where error is going. Something like Rust's '?' operator comes to mind. Also, pattern matching with parameter extraction.
- deleted 4y ago[deleted]
- lowmagnet 4y agoThis functionality is really meant for situations where you do stuff like validate a struct for completeness (part of checking user input, often) and return a list of errors instead of failing at the first error. It's kinda a godsend for the kind of application I write.
- sidlls 4y ago"What only matters is the unwrapping procedure and conversion to string because that is what is needed." This, in a nutshell, encapsulates what Go gets wrong about error handling. The simplicity is great; the extreme simplicity at the expense of runtime efficiency and clarity is not. Errors are not just strings. They can (and should) encode information, and the language should support that efficiently. And the mechanisms Go includes to make it more ergonomic impose small penalties in performance that add up at scale. This "solution" doesn't help that (it makes it worse).
- nhooyr 4y agoThis blog post is inaccurate. The only information an error is required to implement is their string representation. You can add whatever you want on top, there are no further restrictions.
- sidlls 4y agoIt's true that you can add additional information via structs or even just `fmt.Errorf`, but I disagree that the blog post is inaccurate. Fundamentally Go's error handling is very much string-centered. All the extra encapsulation you add via structs implementing the `error` interface just make things worse, because of the poor design to check those types (`errors.As` is a monstrosity).
- lzap 4y agoI was trying to say that eventually, errors in Go distill to strings. Of course the type which represents errors can be anything, I thought it is obvious and it is also mentioned in the introduction section which you may have skipped.
- topicseed 4y agoErrors are undeniably verbose but they incite the developer to consider them, and add context or information to them. I wouldn't say they're a massive issue. Now, enums I find myself missing, and the same goes for parsing dates from strings. Holy moly. Otherwise, it's a straight to the point language and I get stuff done with it. Less tinkering, less overthinking, it just gets stuff done.
- nprateem 4y agoI still feel there's space for a middle ground language. One that: * compiles (ie no interpreter/VM required) * is statically typed and has generics * has exceptions or option types * doesn't have a borrow checker * isn't purely functional but has map, filter, pattern matching, etc * has reasonable traction Is there anything like this?
- Smaug123 4y ago… F#? As of .NET 6, ahead-of-time compilation is a thing, and I am led to believe it's got substantially better in .NET 7.
- pjmlp 4y agoSome correction though. AOT is already a thing since .NET 1.0, but NGEN has always had the inconvenience of AOT on install with dynamic linking. WinRT brougth MDIL on Windows 8.x, replaced by .NET Native on Windows 10. Mono has always had AOT, specially due to Xamarin for Android. Unity uses AOT for C# code, via translation of IL into C++, IL2CPP. Currently Native AOT only supports CLI and libraries, .NET 8 hopefully will support GUI applications as well.
- hocuspocus 4y agoSwift? Maybe Carbon eventually.
- grose 4y agoZig? I think it ticks all the boxes.
- shakow 4y agoKotlin Native?
- valcron1000 4y agoYou're looking at Ocaml
- gilbetron 4y agoThat's exactly the language I want as well. A mashup of Go and Rust that keeps the best of both. Also, don't forget "compiles fast"! And the garbage collector, although I'd love a language that allowed me to handle memory as well.
- 727564797069706 4y agoI once liked Go a lot, then over time got frustrated by few things and moved on. Now I'm all about "Rust is the best thing since sliced bread!" I find it a bit hard to understand why people are critizing Go "yaddayadda oh how wrong this decision is yaddayadda". Like, who cares. Let them do how they like it. Nobody is forcing anyone to use the language. Go's design decisions are not a universally applicable law or anything that you must follow even if you don't like them. I mean, if you're using the language and dislike this decision, then it's a bit different story and I think you should influence the change through the official channels. Probably you've done it already. Fact of the matter is that there are TONS of people out there (and here too) who agree with those decisions, keep using the language and enjoy it. And for that I'm happy for Go!
- cesarb 4y ago> I find it a bit hard to understand why people are critizing Go "yaddayadda oh how wrong this decision is yaddayadda". Like, who cares. Let them do how they like it. Nobody is forcing anyone to use the language. A choice of programming language affects people other than the ones who decided on it. An obvious example is bug fixing and other maintenance; if for instance I find a bug in syncthing and want to fix it, I have to learn Go, because that's the programming language they chose. Another example is finding work; if most employers have systems written in Java, and you don't want to be picky about it, you have to learn and use Java. And finally, the popularity of a language directly affects its ecosystem's health, and since there's a limited amount of programmer time in the world, one language becoming more popular implies other languages become less popular (and after some point, their ecosystems begin to suffer). Given all that, it makes sense that even people who do not like Go want its designers to make good choices (and get annoyed when they make bad choices), since its popularity means that there's a good chance that they will have someday to use it.
- za3faran 4y ago> Nobody is forcing anyone to use the language. Except when your employer does
- saturn_vk 4y ago
- peacelilly 4y agoThe secret to wrapping errors is the erros.As and errors.Is special interfaces called out only in the documentation: https://pkg.go.dev/errors#Is https://pkg.go.dev/errors#Is You must build a Directed Acyclic Graph (DAG) to ensure these special interfaces don't hit an infinite loop. To stop the infinite loop cycles, and actually implement a DAG, I marked visited nodes and returned `false` if the nodes were already marked.
- hellcow 4y agoIf you’re needing to implement this I’d highly suggest your code could be restructured to eliminate the issues. This is a code smell. I’ve been using errors.Is since day one and have never once needed to implement anything like you described. I define sentinel errors in my root “business logic and types” package, and my child packages use those special errors in their own error Is() methods.
- throway23422 4y agoI like the simplicity of Go but it is unfortunate that Rob and Ken were spooked by sum types and pattern matching.