It takes me longer to write Go code because of all the error handling stuff I'm putting in. Then it takes me less time to debug and fix run-time errors, because the error messages that my code generates are informative. I like this tradeoff for production code. This tradeoff is usually a bad tradeoff for throwaway scripts.
I have plenty of experience in other languages, including languages with exceptions and languages with enforced error checking (like Rust). My experience with these other languages has made Go feel a less clumsy.
For languages with exceptions, I often end up with code like this:
SomeType aVar;
try
{
aVar = SomeMethod();
}
catch (SomeError ex)
{
throw new OtherError("description", ex);
}
For languages like Rust, I often end up with this: let aVar = match SomeFunction() {
Ok(x) => x,
Err(err) => return Err(OtherError::EnumValue(someContext, err)),
};
(Yes, I know about map_err.)And in Go, I end up with:
aVar, err := SomeFunction()
if err != nil {
return nil, &Error{"some context", err}
}
This is not meant as a statement about “the correct” way to write code, it’s just meant as an illustration of the kind of code I often end up with, in projects that I work on.It depends on how you write code, what you're doing, and your approach to solving errors. Do note that you don’t HAVE to use the if err != nil approach in all of your Go code. It is not the only method for bubbling errors up. There’s a whole discussion to be had about when it is appropriate to panic()/recover() and why you would choose to panic() in Go, even though people say you’re “not supposed to do that”.
I am curious to hear more about why you prefer what you wrote to map_err, if you're willing to share. I have my own guess, but I'm always interested in things like this.
(For those that don't know, you could write the above code as something like:
let aVar = SomeFunction().map_err(|err| OtherError::from(someContext, err))?;
or if it becomes too long, let aVar = SomeFunction()
.map_err(|err| OtherError::from(someContext, err))?;
and in some cases you don't even need the |err| but since we're taking two arguments here you can't 'curry' it in a sense.)The "match" syntax is very simple, clear, and flexible. I don't have to remember the different Result methods: or(), map_err(), map_or_else(), and_then(), etc. There are just too many methods to remember, and match does everything. (Edit: and it's easier to borrow or move something from the enclosing scope inside 'match'.)
If I later decide that the Err() branch inside the match needs to do something other than propagate an error, I can just change the code there, without having to change the .map_err() to something else. I like match because it's simple, easy to read, easy to write, and flexible.
In Haskell, I’m more comfortable using functions like Rust's map_err because I can, e.g., put it on the outside of a "do" block, and in Haskell, it’s not like you’re going to "break" or "return" anyway (not in the imperative sense). In other words, in Haskell, something like mapError has the same power as "case" does (and perhaps more, since there are multiple ways to propagate errors in Haskell, and mapError will handle all of them, as long as you’re in an error-handling monad).
> you are no longer in the control flow of the parent function,
Yeah, I run into this myself from time to time. I still end up defaulting to map_err when possible and then doing this when I have to, personally, but I can see the logic here.
> I don't have to remember the different Result methods:
I 1000% understand this. I think where I'm personally at is because I do know those methods, I end up doing the opposite: it takes me a second to go "oh, this is just map_err," which is the same problem but in reverse, and someone's gonna have to do it one way or the other.
This is extremely pedantic, but without knowing Go, it looks like it's the other way around: Because you cannot curry the function "from"[1], you cannot do the partial application of "from" to "err" (which after currying would not really be a "partial application" but just application of the outermost function). Hence usage of what looks like a lambda.
[1] I guess currying is just not a thing in Go, because this looks like a straightforward case from a distance?
Just to be clear, I was speaking about Rust here, not Go.
Rust doesn't really support "currying" exactly. What's happening here is this:
The signature of map_err is
pub fn map_err<F, O>(self, op: O) -> Result<T, F>
where
O: FnOnce(E) -> F,
A method that takes a closure that implements FnOnce(E) -> F.I shouldn't have named it "from" because From::from in Rust has a different signature than we needed here, I'll call the version in this code "from_context" instead for the rest of this post:
fn from(T) -> Self
fn from_context<C, E>(context: C, error: E) -> Self
(where C and E aren't exactly this but whatever it doesn't matter from what I'm trying to say here)We have an arity mismatch between these two. FnOnce takes one argument: the error. But in our version, we also want to tack on some context. If we didn't need two arguments, then we could simply pass the function as an argument, because function types in Rust also implement the closure traits in Rust.
.map_err(OtherError::from)?
Is that currying, exactly? It feels like it but I'd argue it's not. It's just a type implementing a trait, just like anything else. If Rust let you do .map_err(OtherError::from_context(someContext))?;
I would argue that's currying support. You can do some sorts of currying in Rust, manually, but it's really awkward and 99.99% of the time you're not doing that.For anyone curious what "currying" actually is (I must say that I, for quite some time, made the mistake of thinking that taking a function that takes n arguments and getting a function that takes n-1 arguments (with one fixed) is "currying", which is not technically true, it's just a good thing you can do after currying):
Currying is the act of taking a function that takes n arguments (or an n-tuple), and returning a new function with only one argument. But that function effectively wraps another function, and this repeats n times. So, you take e.g. this function:
f(x,y,z)
and currying makes this function: g(z)
You see it only has one argument. But when you call that function with its only argument, the result is actually another function: h(y)
There's our second argument. Call that and you get: i(x)
And now you can call that with the first argument, and get the result.So after currying a function, you can just apply the last argument, and effectively get back a function with the last argument "fixed". Without that, you effectively have to use a lambda to fix the argument. (Or a combinator that does it for you.)
Though you will need some sort of lambda or combinator anyway, if it's not the last argument you want to fix, but some other one. Then you have to create functions with stuff flipped around... Functions in Haskell usually take care that the last argument is the one where you'd most often want to fix it to a value.
At component boundaries you typically catch the error and perhaps convert it into a different type; and somewhere close to the user interface level you typically actually handle it in some meaningful way (retry operation, show error to user, cancel other work etc). Here by user interface I don't mean just GUI, but things like HTTP request handlers, terminal UI, RPC etc.
In most codebases that I've seen, error handling (as opposed to bubbling the error up with a bit of added context) is perhaps 1% of cases - whether in Java or Go or C. And in Java, this just means that 99% of cases will "handle" an error by simply calling a function, or perhaps the try-with-resources statement.
Personally, I feel that what exceptions with stack traces get you is going to be the best trade-off between nice error messages in logs VS amount of effort in code spent to detail error paths.
Of course, this doesn't have to be a 100% trade-off, and exceptions still allow you to add extra context whenever you feel it is necessary. Even if you decide to do it 100% of the time, they still act as an excellent safety net, making sure that you can't forget about an error, and need not be more verbose than if err!=nil checks or matches on the Result type (though I admit they do tend to be more verbose in most languages, requiring an extra block for try to be introduced).
err!(err,"Connection to %s failed",serverAddr")
or even return ErrConnFailed{address,err} if err != nil
instead of if err != nil {
return "",nil,Struct{},fmt.Errorf("Connection to %s failed: %s",serverAddr,err)
}
You can't even shorten it to one line because go fmt will "helpfully" expand it back to 3 lines...I do think writing context (whether by error type or "just" text) with each error is the way to go vs "just throw it up the stack and hope for best" but Go syntax fails it in that quest.
Syntax wise it’s not much worse (until you start having multiple possible errors in a sequence when its ugliness scales linearly), but the problem is that you pay the 4-5 lines of boilerplate for zero rewarded guarantees such as “if the first thing failed the second can’t/won’t be attempted”. It feels like a lot of syntax cost and boilerplate boredom without much reward.
Its focus is to be written by the grossly inexperienced, and anyone who doesn't fit that category will miss basic functionality from every other language they've ever used.
I’ve been writing C for at least 25 years, I am extremely comfortable with it and know most of its nooks and crannies, and I do it daily as my job. God I wish it had Monads just enough to stop cluttering my code with error checking boilerplate.
There are many things in computing and everywhere else that we have done for decades, before we got far along enough to be able to stop.
For rare errors exceptions are an alternative, but something has to catch and handle the exception.
Like having a single global `errno` that you need to clear manually? Put this in a file `main.c` (or change the line opening `main.c` to a file known to exist):
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
printf("%d\n", errno);
fp = fopen("does-not-exist", "r");
printf("%d, %p\n", errno, fp);
fp = fopen("main.c", "r");
printf("%d, %p\n", errno, fp);
errno = 0;
fp = fopen("main.c", "r");
printf("%d, %p\n", errno, fp);
}
The first `fopen` call sets `errno` to 2 (edit: really ENOENT, which happens to be 2). The second one should not have an error code but it's still 2 (ditto other edit). The third one demonstrates that the call does not, in fact, change `errno` since the file exists.Even in C it was not "just fine," it caused all sorts of bugs. But the bigger issue is that PL theory has improved since then, why be constrained to the same patterns as before?