result, err := db.GetUser("12345")
if err != nil {
return nil, fmt.Errorf("failed to query user: %v", err)
}
There's an inherent asymmetry between how often those three conditional lines are executed relative to the undeniable fact that error handling is three times the code line volume versus the core business logic. That's not ok; and when I look at the argument phrased like that I find it hard to believe that anyone reasonable can take the stance that its desirable that error handling requires writing substantially more code than The Thing Which Generated The Error In The First Place.Sure, in many cases you’re going to bubble up the error (perhaps a syntactic sugar for this scenario would help), but there are lots of production error handling considerations like transaction rollbacks, response statuses, logging, metrics, opentelemetry traces, retry logic, that you will need to handle in practice, and you will want to handle these differently in different failure modes.
Ensuring software acts in an expected way in the transient 0.001% scenarios is very important. With Go I never run into unhandled exceptions causing software to blow up like I do with large Python codebases.
At first I didn’t like the “if err != nil” bloat of Go code, but now I appreciate its explicitness, it is distinctly unmagical, simple, boring, and works well in production.
func MyFunc() error {
r := db.Get("12345") guard "error Get(12345)"
}
Syntactically really strange, but point being: if a function returns (any, ..., error); 'guard' is a keyword which eats the last 'error', optionally prefixes it with the string in that last keyword argument (standard golang error wrapping: "error Get(12345): {err.Error()}", and bubbles it up (along with zero or default values for the other arguments). It would also be nice, for more complex use-cases, if that last argument could be a mapping function as well, like: func MyFunc() CustomError {
r := db.Get("12345") guard func(err error) CustomError {
return CustomError{baseErr: err, code: 500}
}
}
Though, I'd gladly settle to not have that, as it goes a little beyond the extreme syntactic simplicity I expect out of go.It is ok. That's really how it should be IMO. The "problem" is that Go doesn't allow you to say "eh, we'll just give a stack trace to the user, and then they can delete it print Oops something went wrong" which is apparently what most people want from their error handling.
result, err := db.GetUser("12345": no_user)
no_user:
return nil, fmt.Errorf("failed to query user: %v", err)
If there is an error the program jumps to the label. If no label the program panics. This implied that you have both return and return_error keywords.I have personal experience with Java, Go, and C#, to varying degrees. Over the years, my personal style has changed a lot, based on my experience running applications (as someone in ops), developing applications, debugging applications, etc.
First of all, I'll say that doing Go error handling well figuring out the right place to add context to your errors. So in the example above:
return nil, fmt.Errorf("failed to query user: %v", err)
The error is from a method named "GetUser", and in the style guide I use, errors from GetUser would already say something like "get user %d: %w". You'd know this when writing code that calls GetUser, and wouldn't double-wrap it with additional context, if the additional context is not useful.That's a bit of a tangent.
My experience working in operations is that errors in languages like Java are often stack traces. The stack traces are often large and often have poor signal-noise. Important context is often missing--things like arguments to methods. C++ is sometimes worse, since there's a lot of C++ code out there which won't even give you a stack trace. Worst of all worlds, perhaps.
As I've gotten older, I've moved to a very proactive style of error checking. This style is verbose in all languages, and sometimes this style is much more natural in Go. That's because of the number of times that putting effort into error checking has saved my butt when debugging. By the time I'm debugging a piece of code, it might long forgotten. The error might be hard to reproduce. Getting a good report the first time saves a ton of time when debugging. In other languages, this might be accomplished by aggressive logging, or tools like time travel debugging, or catch & rethrow.
My sense of Go's error handling is that it is a lot of code only if you measure it by line count. The error handling is very boilerplate and you stop seeing it, like when Cypher's looking at code in The Matrix.
https://www.youtube.com/watch?v=MvEXkd3O2ow
In isolated cases, it makes sense to panic() / recover() in Go. People new to Go sometimes overuse panic(), and then once they get more experience they overcompensate and don't ever panic()... I think there's a middle ground here, where panic()/recover() is useful in certain situations. I use it most for parsing / marshaling / unmarshaling code. Parsers, for example, can be very dense, and the error handling is often just "return to top, throw everything away, no additional context to report".
What we need is some education like "case studies for when you might want to panic/recover in Go" or "case studies in where you should add context to error messages".
GetUser can't know the call site or condition that led to the call and this is often the very thing you need. Amending returned errors with useful context is invaluable. Languages that permit this to be done concisely are a blessing: iFailed().expect("and this is why") for example.
> Java ... The stack traces are often large and often have poor signal-noise.
Earlier this week I needed the whole stack trace. The "who (ultimately) caused that to get called" question gets answered quickly by comprehensive stack traces.
I've actually used Java's stack trace behavior for reverse engineering. You can suss the design of some system by throwing something and then reading the stack trace, even when you lack the source code or the time the analyze it all. Good Java programmers know they can structure code specifically to increase the utility of stack traces.
> The error handling is very boilerplate and you stop seeing it
Wait, weren't we being made to think about it, as one of the supposed benefits? If, as you say, we won't see it then that argument goes out the window.
While Java stack traces may be verbose, with even an ounce of experience one will realize that you only have to look at the top message and the “caused by” top messages. The other parts are important when you actually want to reproduce the error — good luck reproducing based on a single “failed to query user” message.
You don't need to blindly annotate the reason for an error every single place an error gets returned. You often end up with redundant errors like this:
> could not load document "doc.txt": error reading document "doc.txt": could not open "doc.txt": open "doc.txt": file not found
So, sometimes you just return an error upwards, sometimes you conditionally wrap it depending on where the error came from, sometimes you conditionally wrap it depending on what the error type is.
And yes, you may be working with poorly-written code that doesn't do this, or you may be working with poorly-written code that just returns some fmt.Errorf() for everything... are you going to parse that? (My approach would be to fix the dependency so it returns better errors, if its needed for good error handling on my end.) Poorly written code is a hazard in all languages--I could just as easily throw RuntimeException in Java if I didn't care how it was handled.
> While Java stack traces may be verbose, with even an ounce of experience one will realize that you only have to look at the top message and the “caused by” top messages.
I can only conclude from this statement that I don't "even have an ounce of experience" with Java. That's extremely harsh! Maybe I'm just a complete idiot and it's hopeless, I should quit my job, or maybe I just haven't put in enough years working with Java.
My first complaint is that the context for an error is not present in the stack trace, because the stack trace only contains the location of the error, and does not tell you which objects the error is associated with (like, which user ID, just to make up an example). That information is either encoded in the exception message (it often isn't) or it is in the log somewhere, although you may not have an easy time finding the relevant line in the logs.
My second complaint is that the top and the bottom of the Java stack trace are usually not what you care about. You care about something near the top (but not at the top), some method which called a method that threw the exception, and you care about something farther down near the middle or bottom which shows the operation the program was doing (but not all the way at the bottom, because that will often just be some generic top-level try/catch).
I'd love to see this. I feel like I often default to adding context to my errors, which is probably better than defaulting to not wrapping at all, but would love to know what criteria you use to determine when adding context adds value
No there's not. People seem to just want to ignore all errors, and let the language "figure it out", AKA exceptions. If you want to ignore errors, then just go all the way and do that:
result, _ := db.GetUser("12345")
then, you never have to worry about errors, you can just code in bliss and wait for the "panic" because you didn't want to bother with proper error handling. func main() {
x, _ := getNonZero()
fmt.Println("Nonzero number:", x)
}
func getNonZero() (int, error) {
return 0, errors.New("oops")
}
The "_" is supposed to be used only when you're absolutely sure that error cannot happen (e.g. the function you're calling is partial, but you know that the input is in the defined set).Ok friend, but right here in this blog post is contrary evidence. The supposed "actual CopyFile function" ignores errors from two deferred .Close()s at the io.Copy() call site. [1]
And this is idiomatic Go. It goes on every day and you can find thousands of examples of it all over GitHub et al. Solving for it quickly leads to a real eye-sore: a deferred closure or similar blight.
So if "think about them" is your aspiration then Go has failed.
Also, I think the other critique is less about forcing you and more about the syntax overload your force onto someone. Rust and swift come to mind as counter examples where you’re forced to handle every error AND the language tries to keep that out of normal code flow unless you are actually having to make some decision regarding the specific error.
The particular syntax for returning an undecorated error is needlessly verbose and takes three lines.
We shouldn’t have to write this say three times in a function:
if err != nil {
return nil, 0, err
}
What happens to the errors from all the "defer foo.CloseOrMaybeFailSomehow()" that get run on early return? Answer: they're ignored. Ignoring errors baked right in. Yes, you can handle them with a closure, but I can count on part of one hand the number of times I've actually seen that. And I know why: because at some point the regression gets unreasonable and people just pretend they didn't see it and thank their makers the compiler lets them get away with it, this blog post in question being a fine example of that.
So I know what sort of malarkey I'm reading when this "think about the errors" gets bandied about.