157 points · by henridf · 7y ago · 145 comments
Standardising error unwrapping is a great idea IMHO and I think that this has a lot of merit.
I don't like the `fmt.Errorf("more description: %w", err)` though for several reasons.
Firstly it is a lot more opaque than Dave Cheney's original mechanism errors.Wrap(err, "more description"). You've got to check the format string for a `%w` to see if it is wrapping an error or not.
Secondly why is this really important functionality in `fmt` and not in `error`?
And finally we've been encouraged to write `fmt.Errorf("more description: %v", err)` (note `%v` not `%w`), so I think there will be a lot of unwrapped errors.
...
I'm not sure enough has been thought about the backwards incompatibility. With rclone I try to maintain compatibility with the current go release and a few previous ones so that rclone can remain running with distro go versions and gccgo both of which are a bit behind. For something as common as error handling this will cause lots of libraries to suddenly be no longer usable with anything less than go1.13.
IMHO I think this would be better staying as a non standard library package for the time being while more kinks are worked out.
Yuck.
`fmt` already depends on `errors`, and Go does not allow cyclical dependencies, so `errors` would have to reimplement string formatting.
Which already exists incidentally, internal/errinternal was added so errors.New and fmt.Errorf could return the same type.
It does make errors pull the entire formatting machinery, but chances are you're probably using string formatting long before errors so meh…
That's an argument for putting it in the language layer or putting it in its own place.
The parallel reddit thread seems to agree too: https://www.reddit.com/r/golang/comments/biexq0/go_113_xerro...
Having been writing software over the 30 years that you mention, it's clear to me that Go has not been isolated from language design, it's just made a choice to stay simple. Java, C++ and Python have exceptions to keep you from littering your code with error handling, and code with exceptions is hard to read. The line of code you are looking at any point in time may instantly jump to another place, effectively, having "goto"'s evil cousin, the "comefrom". Somewhere, in your code, is a "comefrom" statement which runs immediately after the statement you are looking at, you're not aware of its existence. My Java/Python for production code ends up looking a lot like Go in terms of error handling, because you have the most context about an error at the point where it happens, so that is the best place to deal with it. I believe that Go 1.x will have the staying power of C.
Rust and Swift both manage to make error handling easy while keeping this nice "errors are just values" property. Go could easily have added Rust-like or Swift-like error handling backwards compatibly with their existing idioms without falling back on weird special cases of format strings, but have chosen not too.
This does not make the language simple (even though in other ways it is).
It's the same in golang, any line can panic.
Do you ever see golang code that handles errors returned from fmt.Println?
Lisp is simple. Go is half-simple, but in its take on simplicity, it also takes away some constructs that make useful, high-leverage expressiveness impossible.
Some of its other benefits are appealing to me, but that's not one of them. It seems simple on its face only.
Exceptions and return values are both sub-optimal. Exceptions encourage drastic actions for non-drastic events (exit the program if an HTTP server is transitently slow). Return values encourage ignoring the error value, and then wondering why your program broke. Special types that wrap error values or exceptions cause the same problem; when you want to defer something, your code becomes contaminated with the error type (f(x) returns an error, g(x) calls f(x) but doesn't feel like dealing with the erro, so now g(x) returns an error... and all the way it goes up to the top level.)
Overall, I don't see a grand unified solution to this problem. We should make it possible for functions to declare everything that goes wrong so that recovery can be more easily tested. No language does this; they often merge vastly different errors into the same type, so the programmer is powerless to understand the possibilities. Consider two database errors; "syntax error" and "transaction aborted, retry it". Typed error systems typically condense that to a "database error", but how your program should handle the two cases are vastly different.
Anyway, I'm happy with the way go works. If I don't explicitly know how to handle an error, I wrap it with a tag and return it. When I look at the alert / error logs, I know which codepath caused the problem and can investigate. For cases where I know how to handle an error, I can explicitly deal with it (yes, often with strings.HasSuffix to find the one I know how to handle). That is all I really need. If it were an exception, the code would be basically the same. So I think it's a red herring to complain about values vs. exceptions. Neither system prevents you or encourages you to write correct, robust code. If we want to do that, we need completely new tools.
_But_ Rust also includes some really nice syntax for passing errors through so I can write this:
use failure::Error;
fn foo() -> Result<String, Error> {
may_return_an_error()?;
might_return_a_different_error()?;
if some_condition {
return Err(MyPackageError { detail: "..." })?;
}
Ok("foo")
}
The `failure::Error` type automagically wraps any error. That means I can go through many levels of my stack returning `failure::Error` and at any point in the call chain I can decide to examine the error type instead of writing `some_func()?;`, which would pass the error back.The only part I don't like is that I need to add a `?` when I return my own errors. I don't totally understand this but from what I sort of understand the reason is that `?` invokes `.into()` on the returned object, which is what lets me return a (wrapping) `failure::Error` instead of a `MyPackageError`.
The upshot of all this is that "ignoring" errors is quite easy, as long as _somewhere_ in my call chain I actually do handle the error. The type system will enforce this for me, as attempting to treat a `Result<String, Error>` as just a String will cause a compile time error. I have to unwrap it and either ignore the error (which would lead to a runtime panic if there _was_ an error) or do the right thing, which is to explicitly handle both the ok and error cases.
I'm working on a CLI program using this system, and I can bubble all the errors up to the main entry point of the CLI. At that point I can turn errors into a print to stderr and an appropriate exit code.
This is exactly opposite my experience. In 90% of cases there is no way to recover from an error locally and I should just fail at the highest level, possibly retrying a few times.
My point is, a lot of good error handling is built at the lowest level, close to the point of failure. That code knows what the problems are and how to fix them. Errors are not the exception, they are the rule. If you handle it well, people won't even know how unreliable the underlying system is. (NAND flash? The first time I used raw NAND flash I was blown away at how unreliable it was. How do computers even work at all like this, I thought. Then I realized... that's why so much money is poured into things like SSD controllers. To hide that fact from the user and make them happy, even if the raw technology it's built from doesn't offer perfect reliability.)
https://www.theatlantic.com/ideas/archive/2019/04/why-accide...
> Accidents happen. What he meant is that they must happen. Worse, according to Perrow, a humbling cautionary tale lurks in complicated systems: Our very attempts to stave off disaster by introducing safety systems ultimately increase the overall complexity of the systems, ensuring that some unpredictable outcome will rear its ugly head no matter what.
If you don't like it, don't present pale echoes of criticisms we've already seen (not listening to 30 years of language design...), tell us what you would do instead, because the answer is non-obvious and there is no one 'right thing'.
It’s very easy and not very useful to come up with vague criticisms based on generalities, it’s much harder, but infinitely more fertile and interesting, to come up with a coherent thesis as to what should be done. The OP posited a right way, I’m curious as to which of the right ways they mean.
Over the decades as a programmer I have seen a lot of language come and go. A lot of languages suffer from "features". Where either a language is designed with advanced concepts getting either directly in the way of writing simple programs, or even worse, getting bolted on later on, creating something very different from the initial language.
I love the dependable simplicity of Go. It contains everything I need for a surprisingly large part of my work and not offering more than that is an asset. Few things in Go feel like they had been thrown in without proper consideration.
That's clearly not true - they've made plenty of mistakes.
Of course, any humans are making mistakes in the process nevertheless, but overall I think they got it pretty much right.
Having said that, I would be curious what you have in mind when saying that they made plenty of mistakes?
If you like Go, you'll love the simplicity of Brainf-ck, a clean design which is easy to learn, simple syntax, and supported in almost all computing platforms.
Re: exceptions, there are a lot of people, myself included, who do not view exceptions as "advancements", but as setbacks. Magically and suddenly subverting the normal control flow and unwinding the stack in highly concurrent programs (as is expected in Go) is an awful way to do error handling, and you end up having to bypass that mechanism and pass the errors as values across call stacks anyway, so what are you really gaining for all the extra complexity, "implicitness", and cognitive load of doing that?
The Go team's "Draft Design" (with check/handle keywords) somehow omitted a requirements section...
https://gist.github.com/networkimprov/961c9caa2631ad3b95413f...
So then why do you use it extensively?
Dart struggled for years to find a killer app, though Flutter now seems to be a good bet.
Originally the idea was to replace JavaScript and everyone except TypeScript pretty much failed at that. (I mean failed from a popularity point of view, they often succeeded technically.)
I'll also point out that coming from Google is kind of a mixed blessing these days, from a popularity standpoint.
Also since Go is "hypocritically Object Oriented", people can claim it's not an object oriented language and kind of write Go like classic structured programming such as C. But Go is OO. You can't write go without using interfaces for I/O.
There was a precursor to golang that the some of the same authors worked on before they were at Google. It didn't go anywhere, precisely because it didn't have Google's name behind it.
For example its CSP concurrency model, similar to Go, was hardly pertinent when common processors were 150 MHz Pentiums with 1 core. Completely different scenarios.
Not to mention Bell Labs had enormous influence on Computer Science at the time so it's not like Limbo had no strong backing either.
I suspect that the overwhelming majority of Go developers has no idea this is in the works. It was covered once on the blog last August in the Draft Design summary, when there wasn't any code behind it. It was not mentioned in Go 2 Here We Come[2], nor at the start of the below golang-dev thread. It was mentioned on golang-dev when I posted a link to the issue tracker in late January, but my posts would see a fraction of the attention vs those by Rob, Robert, Russ, Ian, et al.
There are outstanding issues with the current draft, specifically its performance[3] and API[4].
If it lands in 1.13, please give it Experimental status, with a build or env flag to disable changes to existing APIs, and perhaps a way to re-enable them on a per-function or per-package basis.
[1] https://github.com/golang/go/issues/29934
[2] https://blog.golang.org/go2-here-we-come
[3] https://github.com/golang/go/issues/29934#issuecomment-48650...
[4] https://github.com/golang/go/issues/29934#issuecomment-48350...
.
[Originally posted on golang-dev, in response to "Last call for feedback on Go 1.13..."]
https://groups.google.com/d/topic/golang-dev/jPY0RYXSvCU/dis...
> If the last argument is an error and the format string ends with ": %w", ...
This seems like a magic-string kinda hack to me. I like the idea of wrapping errors so that you keep the stack and full context, especially since you may need additional structured data from all errors (e.g. DB error, access error, ...) to produce user facing messages, so IMHO the wrapping should be more explicit than just %w.
(I'm not defending it so much as explaining it. I'm not sure how I feel about it myself.)
I missed that. How else do you wrap an error with xerrors?
return errors.Wrap(err, "read failed")I expect we will get used to it pretty quickly.
Fill in the blank "Well basically what happened is ___________"
For example i've found this has helped me to go from "Invalid phone number" to "The phone number needs to be 10 digits"
More on the topic, I'm really happy to see this coming in so far ahead of 2.0. I want to get ready for 2.0 because of the gains I hope to see in idiomatic go in 2.0.
I'm not sure I understand why this is something you need to do. "Figure out a way to stop storing what you don't need." Who cares if you don't need it, or at least don't need it now, storage is cheap.
Source: I worked for Microsoft on C# projects where GC was constantly the bottleneck. Reducing number of exceptions (especially those used for control flow) helped.
Looking forward to shit storm once they introduce generics in near future. I am sure people will still complain that this is not how parametric polymorphism should be implemented.