474 points · by robfig · 7y ago · 408 comments
It's a language intended to have few primitives with an emphasis on code being transparent and errors being values, requiring you to think about what they might be at each point as you're forced to carry them up the chain.
Do I particularly like managing errors that way? No, but I do think that it improves the transparency and quality of a lot of Go projects.
The same goes with the Go ecosystem and tools. You might not like how gofmt forces your code or the documentation conventions used by golint but the fact that we all use the same convention and documentation is awesome and it's what allows things like godoc.org. I think the proverb is "gofmt's style is no one's favorite, yet gofmt is everyone's favorite".
And things like the lack of abstractions and generics are what create a community that's less reliant on dependencies. "A little copying is better than a little dependency" and you can see it in stark contrast to something like the JS community with its require('left-pad') NPM ecosystem.
So, yeah, I like that they didn't fragment the community around something as arbitrary as this. And I get that some people won't like it, just as they don't like the lack of generics, but there is strength in some of these approaches that isn't immediately obvious.
So long as we can all agree that it feels super bad, I guess this is fine. But it does sort of mean that Golang approaches the Java world back with checked exceptions where principle trumped ergonomics.
That lead to a world where folks felt "forced" to use Java, and that's a sticky label that's difficult to remove. I think the Golang community is going to find itself growing more slowly as folks increasingly realize other options offer similar benefits without the bad ergonomics.
Because I can't stand Golang error handling. It's repetitive, it's error prone, and other language features interact with it so that when you make a mistake it can be as hard as a double free to track down where the erroneous default value was introduced.
On the other hand, using Rust, Ocaml, F# or Haskell I understand how my code composed and I can be confident I can just use an error handling strategy. The only complexities appear, as with everyone else, when we have asynchronous code.
So I don't mean to disagree with your feelings, but they're sure not mine and they're part of why I don't use Golang. I was excited about try() because it at least addressed the most tedious part.
You didn't have to because there is an precise, robust non-checked exception handling system which takes care of that: the hardware catches the situation, dispatches a handler in the operating system which fixes it and re-starts your program at the original machine instruction to try the memory access again.
Could you give an example?
I think you’re talking about something different than what I’m understanding. One of the major frustrations I have with Go error handling is the lack of stack traces, which means I often have to modify code in order to find out where an error occurred.
I’m pretty sure that’s not what you’re talking about, though.
My impression of go, is that it is very boring to program in it, and some decisions weren't thought well. For example if you use anything else for numbers than int, int64 or float64 you will have very bad time. Lack of generics forces you to duplicate your code, duplicating increases chances of errors and make it harder to fix bugs. The errors are passed as values, but then you need to use different return value to pass them, defeating the whole point of having that. On top of that the language is very rigid.
I'm wondering if introducing macros could solve a lot of those issues.
Same could be said about assembly language.
Don't you just mean you knew where fatal exceptions could be raised? That's substantially different from "fail".
Personally I enjoy writing Go code similar to the way that I enjoy writing Python code. So they did something right because I wouldn't ever say the same about Java or PHP.
Edit: As a fun tangent... Python experienced the same kind of fracturing that adding generics or other dramatic features to a language can cause with the 2to3 move. There are still projects based on 2.7. It was hard to get people all on the same page once the community was split. What's also interesting is to watch the same thing happen with asyncio, which is practically an all-or-nothing thing to use in your Python project, so much so that most Python code still doesn't use it. Just an observation, but breaking changes to a language can really do a number on the community.
For example, the semantics of the for-over-collection statement in Java are that it repeats the block of code, with the loop variable holding each value of the collection in turn. In Go, the equivalent statement also needs to document what it means to take the reference to the loop variable. Composite data types have semantics for taking references to sub-parts (struct and arrays/slices allow taking references, maps do not).
Slices and arrays are another complicated area of the language, with gotchas like append sometimes modifying the original array, sometimes not.
Regarding splits, you still have that in Go as well - do you use goroutines as coroutines, sending copies of objects through channels? Or do you use them as threads, with shared memory and locking? Do you use the testing package as is, with its lack of any user-friendly asserts? Or do you pick up an assertion library? Do you use raw http,or something la Gorilla? Sql or some ORM? Do you log to stdout, or do you pick up a logging library?
Regarding gofmt, I personally can't understand the passion some people have for enforcing a common style.
Regarding build tools, Go is hardly unique among modern languages in having built-in tooling for that. It's relative ease of deployment also means that Go's build tools can't be used alone in a multi-language project, so many of the apparent simplicity is only useful in a subset of projects that actually use only Go. Even then, if you have any other build artifacts you may find you need to reach for something other than Go's tooling. By comparison, Maven can easily handle a Java+minor bits-in-other-languages project out-of-the-box.
Not to mention that Go is probably the only language in any kind of popular use today that doesn't have a built-in way to interface with C code (you need to use a separate compiler if you want that!).
To me, Go has a single killer feature: binary and memory size for a GC language. And Java may be catching up on that area...
That's also why I think Go will forever be a "to each his own" language. By targeting that lowest common denominator, choices are made for you, some people will always dislike it, and others will always love it.
Actually, I don't think everyone agrees it feels super bad. I personally like having all of my error handling be explicit, painfully explicit even.
>approaches the Java world back with checked exceptions where principle trumped ergonomics.
I also have to disagree here. To me, checked exceptions are the worst of both worlds. Here you have additional language features, but nearly the same verbosity. Your 'happy path' must be surrounded by try blocks. Worse, everything that happens in a try block is 'flattened.' Not only does this mean you may need many try blocks, sometimes it can even be difficult to take individual statements and put them in one try block. For example:
try {
doThing(doOtherThing());
} catch(...) {
// What happens if doThing and doOtherThing throw the same exception? Do I have to use a temporary variable?
}
Also, exceptions have been overloaded to handle everything, including runtime errors. I think this is more subjective but I strongly dislike it. I do think runtime errors should be possible to handle, just ideally through a separate, more explicit paradigm. try {
doThing(blah[0]);
} catch(...) {
...
} catch(IndexOutOfRange) {
// Handling runtime errors at the same level as application-level errors!!
}
Go doesn't even really force you to check your errors, it just makes it harder to accidentally not check them. Like: result, err := doThing(); // Error
return result
result, _ := doThing(); // NOT an error
return result
I think this is excellent. It may lead to complaints about an annoying compiler, but most importantly it leads to fewer mistakes. You can still explicitly tell the compiler to shut up, but it is obvious.Language ergonomics are complicated, but the benefits of Go's approach are hard to deny. Unfortunately, nothing comes without downsides, and it seems like solving the error handling ergonomics issue is a tough one. I think repetitiveness aside, the Go error handling ergonomics are great, and that's exactly why they attempted to reduce repetitiveness. But, in reflection, a lot of that repetitiveness can also be reduced by refactoring your code, so it may not even be quite as bad as it seems.
Go has exactly the same issue. But with exceptions at least you can group multiple statements together and handle them with one catch block. With Go you have to use multiple if blocks to get the same semantics.
> Go doesn't even really force you to check your errors, it just makes it harder to accidentally not check them.
Go doesn't make it harder to accidentally not check errors. If you call a function that only returns an error, such as os.Mkdir(), then the compiler will not warn you when you forget to handle the error.
> Language ergonomics are complicated, but the benefits of Go's approach are hard to deny.
I don't really see any benefit to Go's approach over exceptions or result types. If making it obvious that errors are handled is important, there's a solution for that that's much more elegant than if-err-nil blocks everywhere. It's precisely the solution that the Go community just rejected.
Not if you're doing it right, which means bubbling up (read: adding the exceptions to the "throws" clause) exceptions that you can't handle _then and there_. You leave the "real" exception handling to the code that's closest to the end user and can actually handle the error in a meaningful way.
For example, in this pattern when you implement the business logic in a REST service, generally there's no catching at all, instead the exceptions are declared as rethrown and way up the stack you would have a global catch all that serializes the errors into JSON and sends them to the user. Simple. In Go you're forced to do "if err{}" checks everywhere, particularly in your endpoint's business logic. It's actually _way less_ verbose and burdensome in Java if you do exceptions the right way.
I dislike it because it does the opposite, it makes it too easy to accidentally continue execution when there is an error:
doThing(); // Error
doOtherThing();
Which isn't possible with Exceptions.The only thing that would signal that error handling is missing is the absence of boilerplate to handle it, which is an ugly UX for a language to rely on esp given there's no indication from scanning code that all methods that return errors are handled.
Quite the opposite. You have to explicitly ignore exceptions, whereas it’s easy to accidentally miss an error in Go. For example, how many times have you seen this?
defer f.Close()
Close() returns an error; this code ignores it. result, err := doThing()
if err != nil {
return nil, err
}
result1, err := doSecondThing(result)
return result1, nil
Will not trigger a compile time error.With the amount of boilerplate in go that is simply about bubbling up error codes, it really doesn't seem that much cleaner than Java exceptions. An if block just as many lines as a catch block but again, you lose the typing.
And the more I think about it, the more I think well written Java is cleaner than well written go simply because the throws keyword leads to strictly less boilerplate. I feel like this stigma is simply about how much bad Java exists (and there's a lot). I can't help but feel like a WebSphere written in Go would be just as ugly as its current Java incarnation.
I'm not sure I follow your argument about Go "approaching" checked-exceptions in Java. Nothing is being forced on you. Go has worked the same way for a decade now. There is a lot of hugely successful software written in Go. In all that time, errors have worked the same way. In terms of choosing principles over ergonomics, in fact the Go committee chose ergonomics over the mistaken principle that "explicit error checking is so ugly and onerous that it's worth adding magic behavior and removing clarity".
In any case, no one is arguing we shouldn't or couldn't improve Go's ergonomics. Rather, the conclusion from people who work with Go every day and are happy with the tradeoffs for their particular projects was that this specific change would make more things worse than it made better.
Exceptions feel super good, even as you're taking too many shortcuts and glossing over things. Proper handling of the unhappy paths is often going to feel like a slog, because it often is complicated, and it's often a slog. Glossing over error handling in golang can feel bad exactly when it should.
I'm not sure I follow this talk about "short cuts.". Exceptions provide stronger guarantees by default than multiple-value-bind and manual if statements. Your code fails closed as opposed to open.
> Proper handling of the unhappy paths is often going to feel like a slog, because it often is complicated, and it's often a slog.
I'm used to languages where this generally isn't the case, but sure. Why twist the knife in the wound though?
> Glossing over error handling in golang can feel bad exactly when it should.
When you capture but fail to check an errval and an untraceable default value starts rattling around inside your code causing unexpected behavior? It's like an NPE but worse because it won't immediately trap. It's more like a double free.
I'm curious about what you think these other options are? There are of course tons of languages and you can find just about any set of features you want, but the combination Go has along with the momentum, community, etc. it has means that there are not many that can compare in its niche.
Ignoring the language/semantics (ie. the bad ergonomics) and just focusing on the external aspects. Which languages targets the same niche that have the "similar benefits" of fast compile times, static builds, great tooling, good/improving libraries, easy deployment, and mainstream backing/acceptance?
Kotlin is now the official language of Android, and is being very rapidly picked up all across the Java ecosystem. Oh but it also compiles to JavaScript and LLVM native binaries if you don't want the JVM.
The syntax and ergonomics of Kotlin are great. Really nice language. The compiler is also very fast, just as fast as Go's I believe. It does incremental compilation and all the mod cons.
Which is? "devops"? Otherwise, offerings on the JVM and .NET are strictly superior. And now with native compilation being available for both platforms, they will also be a better fit at devops than golang. Other alternatives include Rust.
It might be fair to say the ergonomics are suboptimal for the code _writer_, but I would say they are much closer to optimal for the code _reader_.
Enjoy your ecosystem, I'm going to continue to use languages that actually like me, and care how my experience is.
For that comparison to work, java would have needed to only have checked exceptions, with some added language features to deal with them cleanly, and then it might actually have been a viable design. Littering your code with try-catch is what makes exceptions infeasible for error handling.
Should I compare it to "Golang Dependency Hell Claimed My Project?"
> For that comparison to work, java would have needed to only have checked exceptions, with some added language features to deal with them cleanly, and then it might actually have been a viable design.
Why? That's not what happened with Golang's error handling?
I could live with a runtime exception, or perhaps an API that differentiates parsing "potentially not-parseable JSON" and "JSON I can vouch for".
I honestly don't see the big difference between littering your code with if/else blocks versus littering them with try/catch blocks. Can you elaborate?
void foobar() rethrows IOException as AppException rethrows FooError, BarError as WtfError {
Being able to express that a bunch of internal exceptions should be wrapped in an application exception would save a ton of boilerplate.The exception syntax itself is also clunky. If you have a complex expression, you have to extract it and assign it to a variable. But you still have to declare that variable outside the try/catch. And, of course, every exception requires Yet Another Class Definition. I'd do:
class SomeClass {
exception ThingBroke handles ArithmeticException;
exception DatabaseDown handles SQLException;
void method(int a) {
try {
int x = (555 / a rethrows ThingBroke) + (getNum() rethrows DbDown);
} catch(ThingBroke e) {
I think the other issue is the separate hierarchy for unchecked exceptions. In theory, they were supposed to be issues you couldn't recover from, thus the correct response was to let the caller fail. But now UncheckedIOException is not a subclass of IOException.Maybe a better approach would be to add an Unchecked interface, though from my reading of the source for exceptions, they seem to be very brittle and maybe there's just no fixing it.
And even C++, after dropping exception specifications in C++17, might get a simplified version back in C++23 as part of value based exceptions proposal.
Though with generics we could have the error values be less invasive. Learning the Scala mindset was eye opening. For e.g. the design patterns of an Optional[T]’s primary code flow are the same as a Try[T,E].
With common transformation idioms, you learn to recognize code patterns the same way one might recognize data structures. It’s no less magical and it simplifies greatly.
I don't see this as an either/or situation. There's a continuum between do whatever the hell you want C and rigorously defined Idris code. Picking a spot on that line involves many trade-offs and everybody has to choose what's right for their situation. That means Go approach is sometimes superior to the Scala approach for a certain class of problems in certain domains.
Edit: don't downvote me, tell me how I'm wrong.
Being close c means you discover errors at run time, then you have to come back to cover them.
All of this is also true of the generic implementation with Result. Except that (IMO) it's much nicer to work with.
> that's less reliant on dependencies. "A little copying is better than a little
> dependency" and you can see it in stark contrast to something like the JS community
> with its require('left-pad') NPM ecosystem.
The dependency-hell of node projects is in no way whatsoever related to sensible, accepted programming paradigms like generics. Their absence from Go is a widely accepted shortcoming of the language. It doesn't make Go a bad language, and it doesn't reflect on you or anyone in the Go community who enjoy using the language, but you don't have to try so hard to rationalise their absence, especially since they're one of the more prominent things in the Go 2 drafts.
Maybe something like vectored error handling (like in Basic) would fit the language better - was curious why Golang didnt implement that - seems a natural pattern their model would work well with.
Is it fair to compare external packages to core language features?
There is nothing preventing a go mod/dep left-pad
You need a value that is either correct or an error, not something that returns two values.
Along these lines, I would have much preferred to see the opposite of this proposal: the total removal of named returns. They add magic and confusion, and they are redundant with normal returns. Except in the absolute simplest and shortest functions, I always reject named returns during code review. They are currently the only example of C++ style policy declaring we-don’t-use-that-feature-in-our-org I’ve run into with Go. Try/check would’ve been the second.
"A little copying", "less reliant on dependencies"... do you even vendor bro
Very refreshing for novice to agree on expert on a topic.
If so, where’s (s)he buried? :-)
https://go.googlesource.com/proposal/+/master/design/go2draf...
You can emulate this with a boolean flag in your RAII types in Rust or C++, that's set or cleared immediately before a successful return, and then doing conditional logic in your Drop/dtor. Or you could do a std::mem::forget before successful returns. But I guess they think this is an important enough case to dedicate syntax to it for ergonomic reasons, which Rust doesn't have - which is what I think they're getting at.
You can use the match construct for that, and the Result<T,E> type comes with some utility methods that make it easier to clarify your desired semantics in many cases. The page complains that the "match" syntax is clunky, but I'm not that sure how 'handle' is supposed to be better.
I think Go sometimes swings too far in the simplicity direction, not letting consenting folks choose to use shorthand, but that’s a very valid design decision.
For example, the example returns a custom wrapper around the original error with context that it was a copy operation with such-and-such source and destination. The equivalent in Rust using `failure::Fail::with_context` requires writing the `.with_context(|_| format!("copy: ..."))` on every expression that uses `?` (unless you happen to get lucky and all the inner errors are the same type, so that you can use combinators to combine them into a single `?`-able Result).
Edit: And to be clear, this is not limited to `failure::Fail`. Using your own `enum Error { Copy { source: PathBuf, destination: PathBuf, inner: Box<dyn Error> }, ... }` still requires you to write a manual `.map_err(|err| Error::Copy { ... })` after every Result value that you intend to use `?` on.
Seems either off-base or poorly worded.
Unfortunately, the community that has sprung up around Go is more or less opposed to new language features on principle.
I think this comes straight from the original go team. Rob Pike had a talk[1] that is partly about why go doesn't keep adding features and why it doesn't have certain features that other languages have. I think people who like go have bought into the idea that the go team has made good trade-offs to make go code easier to read and maintain at the expense of expressibility.
There's a lot of value to there being "one way to do things", even when it's not the best way from any particular point of view.
Go holds this principle higher than most other languages and I think that should be either embraced, or one should look elsewhere - and I'm saying that as someone who "looked elsewhere".
I suspect some people are. Languages have network effects, which get stronger when FFI is uncommon. My team and codebase mostly keep me on Java even though I find Kotlin clearer in every way and I'd love to get better with Scala and Haskell. If for some reason my team switched to something like Go or VB I'd have to find another job or else put up with it.
Using a programming language is not always an option.
I really like how errors are handled in Go and I hated this proposal.
The current implementation forces you to constantly think about errors at each single point and it is extremely good at standing out. This is something very valuable, not something that requires or needs to be hidden behind syntactic sugar. It improves the readability of the code and the quality of the software.
If it ain't broke, don't fix it.
Here's the thing, some of us don't want Rust. It looks great! It's perfectly awesome for it's primary domain (i.e. re-implementing critical portions of a modern browser). But it's not what I want to use as my daily driver.
I'm writing stupid shit that's munging CSV files and transforming json documents. I want a language that mostly gets out of my way, but performs well and can scale beyond a couple thousand lines of code. Go fits that space nicely, even with its (or maybe because of) conceptually imperfect error handling.
I also spent a significant amount of time discussing with many people, including the Go team, and I am glad the proposal was declined, not because I like “if err != nil {…}” but because the proposal to add “try()” was not solving a good problem. Many, and I would say, every Go programmer wants better error handling, but “try()” was not it.
I hope the Go team keeps exploring other ideas to hopefully one day have a better error handler.
Usually to support this the language needs Enum support and a proper type system neither of which golang has. So I'm ok with the developers just baking in syntax for an error monad with specific sugar for extracting the value or handling an error.
Special purpose syntax can buy you a lot more. For example Swift’s try makes it obvious which statements contain error handling without burdening each expression.
That is, the verbosity would certainly benefit from some sugar, but the semantics -- errors managed by separate expressions/blocks immediately adjacent to the error-generating code -- is fundamental to the language, and one of its great strengths.
I often get the feeling that Go users are implicitly comparing it to languages like Python or JavaScript.
I've watched a client try to debug a Go codebase they had. It was sad. Their web server just returned 500 Internal Error and they tried to track down why from logs, but by the time the error had made it back up to the serving loop most information about where it came from had been lost. I suggested they attach a debugger to a server to see what's happening, they said debuggers don't work that great in Go and so people don't use them much.
If they'd been using exceptions they'd have a stack trace and could have pinpointed the source of the fault in seconds.
Tell me again how easy it is to debug Go. In other languages the compiler can just tell me in _seconds_ that I done fucked up.
If you response includes "You're doing it wrong if you have deeply nested framework code" then you can rightly fuck right off too.
I hope they take another stab at improving error handling. I like Go a lot and do think error handling is one place it could use improvements.
It would also appear to be amenable to an automated tool that would convert to or from try-style.
Given that, why would people have strong feelings against? Because they think go needs something better, and if this passes, they'll never get it?
I agree with this. I think many Go users like Go because of its simplicity that prevents unnecessary bikeshedding so prevalent in other languages.
More that they will never get rid of it, even after something better comes along. Same reason Go has been careful about adding generics. There have been many generics proposals over the years. Any one of them – or even all of them – could have been implemented, but all of them had faults that the Go maintainers did not way to forever saddle the language with even when a better way to do generics comes along.
Worse yet, Go community may develop, or already has, a taste to the lack of genetics. When a really really good proposal comes along, and is implemented, it may produce a Python 2/3 rift with the existing code bases, or not be accepted at all because of this.
I don't have a strong opinion on try, but this is not a good philosophy. Whatever you include in a language will get used and will get abused if it can be abused.
This is mostly why there is a part of Golang users who do not want generics. Look at codebases in C++ and you can see the clarity cost of adding generics in a codebase.
It complicates the language for little gain. It's good that they punted on this for now.
https://pbs.twimg.com/media/D_ojiEqUYAAhmrH.png
edit: s/%s/%d/ but you get it.
I was pissed at first. However, now I cannot code in any language without overusing try and being scared of each line.
Using Go's error handling is actually making your code smarter, I mean, you don't want your code to break with a weird message because of something stupid.
The simplest example is adding a default-path whenever I'm reading a file, Go's error handling reminds me of what to do if this file doesn't exist! Or cannot read etc.
Don't take my word for it, Go ;) try it.
with {:ok, val1} <- happy_path1(val0),
{:ok, val2} <- happy_path2(val0, val1),
{:ok, val3} <- happy_path3(some_val) do
function_might_crash_let_it_crash!(some_val)
happy_result()
else
{:error, :enoent} -> handle_notfound_error()
{:error, :eperm} -> report_permission_error()
_ -> raise("don't worry this process is supervised, let it crash!")
end
low cyclomatic complexity makes for a nice user experience, and you learn the philosophy of "if it doesn't work, just turn it off and on again". Why be scared? Just let it go. The VM has your back. func do(a Param) (res Result, err error) {
var aPrime T
if aPrime, err = getResource(a); err != nil && err == RecoverableError {
aPrime = definitelyNoErrorAlternativeGetResource(a)
}
var aPrimePrime T
... // many more steps
return doSomething(aPrimePrimePrime)
}you can manage it a few ways in Elixir, struct matching is one:
def perform(param) do
res =
case get_resource(param) do
{:ok, val} -> val
{:error, %RecoverableError{alternative_value: val}} -> val
end
do_more_things(res)
end Result do(Param a) throws Exception {
T aPrime;
try { aPrime = getResource(a); } catch (RecoverableError e) {
aPrime = definitelyNoErrorAlternativeGetResource(a);
}
T aPrimePrime;
... // many more steps
return doSomething(aPrimePrimePrime);
} @spec my_fn(a::input_type)::{:ok, res::result_type} | {:error, any}
def my_fn(a) do
a
|> get_resource
|> case do
{:ok, result} -> result
{:error, :recoverable} -> get_alt_resource(a)
err = {:error, :reallybad} -> throw err
end
|> many_more_steps_might_have_similar_pattern
catch err
err
end
However what you presented seems to me to be an antipattern. Sometimes code clarity trumps terseness; in this case the results from get_resource and get_alt_resource are categorically identical. If we are allowed to refactor to be actually sane code and not require everything to be in a single function: def my_fn(a) do
with {:ok, res1} <- resource_wrapper(a),
{:ok, res2} <- next_step(res1), ...
case
#handle errors here.
end
end
@doc """
fetches resources of type `your-favorite-type` which
can either come from `get_resource` or `get_alt_resource`
"""
def resource_wrapper(a) do
case get_resource(a) do
ok = {:ok, a} -> ok
{:error, :recoverable} ->
get_alt_resource(a)
# note with this code if alt_resource
# gives you an error tuple you are still
# good to go
err = {:error, :fatal} -> err
end
end
seems much more saneRust's `match` also does an ok job
try {
var val1 = happy_path1(val0);
var val2 = happy_path2(val0, val1);
var val3 = happy_path3(some_val);
function_might_crash_let_it_crash!(some_val);
return happy_result();
} catch (NotFoundError e) {
handle_notfound_error();
} catch (PermissionError e) {
report_permission_error();
} catch (Exception e) {
throw new Exception("don't worry this process is supervised, let it crash!");
}IIRC, the VM exits, so, it's not at all identical. There are potentially severe nonlocal effects and you're already coding defensively by putting a catch/rethrow.
And now years later I couldn't imagine going back to using exceptions. The non-linearity of exceptions creates such a cognitive load of picking up unfamiliar code, and this is where go really shines. I can dive into almost any go codebase and get a lay of the land very quickly.
On another note, I've been enjoying rust's approach with Result<T,E> / the ? operator. Same principle with less visual bloat.
For the record, the `try` proposal which was just declined, is almost equivalent to the `try!` macro in Rust, which was the "testbed" for the `?` operator.
Personally I find go error handling okay but that’s because I exclusively use panic().
I've published plenty of Go code with a panic() here or there to handle fatal issues, and there's never a shortage of ignorant fools dropping in to lecture me.
If I'm not supposed to use it, why is it even in there? To tempt me? That would fit with the glorification of pain and boredom, I guess.
Curious, are there full-time (or at least Primary) Go developers that are upset by the lack of Try?
I use golang at an employer. error handling in golang is verbose, error prone, distracting, and difficult to make sense of when there is actually an error (composing). I've seen on several occasions now errors being mishandled (either dropped by accident, or by overwriting already existing error variables in the same scope). These issues don't happen with exceptions.
About overwriting, again this has never been a problem for me (as far as I can recall). Error values are very much localised in almost all Go code I have seen and written. If a function returns an error it is either immediately acted upon or returned by the caller. As such, any overwriting done at a later stage is more or less for convenience sake.
Instead of designing a language that prevents errors from being dropped by accident, hire a bunch of literal gophers to search your codebase for inverbosity. Good plan will work 10/10 times.
I am a full-time Go developer. Error handling in Go is miserable. `try` would have made it slightly less miserable.
GoLand gets around this somewhat by adding in the Live Template of "err" being a macro expansion for the if err != nil { return }. However, it still adds those 3 lines below each requisite call.
If they added a new keyword that took the place of this macro, would that be too intrusive? Clearly, this only works if you have named return values.
It would be nice if there was a bash/Ruby-like chaining, such as:
var1, var2, var3, err := call1(args) &&
var4, var5, var6, err := call2(args) &&
... and more calls and so on ...
return callN(args)
Where "&&" would perform the if err != nil { return } in-line. Should the first call return a non-nil error as the last argument, flow would be returned to the caller. If not, the flow continues as normal.This could even be extended in the case of function chaining:
return call3( call2( call1(args) && ) && )
The downside of using && is that it's overloading the && and may cause some compiler/developer confusion. This was just an example based on a familiar use case (bash); another token can be used.Rasky suggested something like this based on another proposal in the thread, but using "?" instead.
Another way to approach this might be an overlay language analogous to Kotlin. There could be a Go dialect that compiled into Go that provided this feature. Or, possibly an optional "plugin" for go's compiler that added an intermediate transformation step prior to compilation based on new keywords, but this will frustrate debugging and lead to other surprises. Generators tried to do this, but it doesn't seem to have taken off, from the repos I've read.
Just my 2c
In Python or Java, you see a lot of try-catches around blocks of code, which can obfuscate where the source of the error is, despite having particular handling for the type of error.
For systems code, I mostly care about whether something failed... like: - Was the socket opened? - Was the file created? - etc.
Apparently (early) Java was designed in much the same way, just to a lesser degree.
I'm not a fan of languages specifically designed to limit me from expressing myself. Then again, I work on small/disciplined teams, where this tends to work out pretty well.
Lack of abstractions (a.k.a "cleverness") on the language level, pushed developers to abstraction on the code level, often based on reflection and supported by XML files and (later) annotations.
In retrospect, by avoiding cleverness in Java, we ended up with multiple incompatible framework dialects which implement their own cleverness.
Go avoided this fate so far by having weaker support for reflection, and since the collective developer memory of Java framework excesses is all too fresh. This makes Go code more readable than Java on average, but I don't think it's any more readable than idiomatic code in a high-abstraction language like Rust, Kotlin or Swift - once you learn and internalize how these languages work.
Citation needed.
> we ended up with multiple incompatible framework dialects which implement their own cleverness.
The trend for a while now is using libraries on a per-need basis. E.g. [1]. This also doesn't sit with reality based on the different JEPs available, and standardizations like JPA.
> but I don't think it's any more readable than idiomatic code in a high-abstraction language like Rust, Kotlin or Swift
I haven't used Swift of Rust in a significant manner, but golang is way less readable than Kotlin, and modern Java (8+).
It's just that I personally do not want to work on a project for which the technical need to repeated uncreative execution. I want to explore new ways of solving problems, and Go is not the language for that. That's why use of Go is a reliable signal.
Not being creative about error handling (for example) frees some of the creativity budget for things that I personally find much more interesting.
I like my tools and projects I work on follow the exact opposite philosophy but I do see your point. It can be a lot of fun when the tools allow you to be creative. It's just that when working on real projects, I'd hate to be the person trying to understand someone's clever solutions. I dread it actually but may be that's just me.
I feel some in the go community have become convinced that the “go way” is to write the same code over and over again.
Implementing try now is splitting the community and introducing what will likely be new technical debt. It doesn't fundamentally change things, it only makes the language more complicated in a way that's both weird* and likely to become obsolete once generics are a thing.
They should focus on xerrors for now and wait until generics are implemented and try again.
* weird as in there are no macros and there's no other language construct that behaves like this so it's a totally unique and new thing for Go
Which I think is worse then try.
In a broader sense I am deeply irritated by the part of the go community's culture that seemingly sees any effort to make go more "don't repeat yourself" to be making it more complex. With no acknowledgment that avoiding complexity in the language isn't a free lunch, it comes at the cost of complexity in the code written, the ecosystem and libraries.
I'm "community" and I would prefer to have `try()` than not to have. They didn't listen to me.
It is impossible to implement every proposal their ears listened to so obviously that's not what listened means.
I created my own proposal that I think addresses the issues. I would love some constructive feedback. https://github.com/golang/go/issues/33161
It wouldn't have been the end of the world but I'm glad to see Go still has alive the spirit that made it so popular in the first place.
/cheers
What the try() proposal gets wrong is that it tries to automatically bounce the error back the stack, being equivalent to "if err != nil { return }", which is ofte reasonable, but at the same time lacks the flexibility that current Go code has in terms of augmenting the error, or indeed handling it: You'd end up with try() calls for some things, but not all, so it's just ironing out one wrinkle and not every wrinkle. The second argument to try() is too heavy-handed. What we need is easy, readable syntax for all cases.
In current Go code, people like the "v, err := someFunc()" syntax because it allows the happy path to stay in the current scope, with the secondary syntax "if v, err :=" introducing a new scope to avoid polluting the parent scope. If you're in the current scope, your code stays flat and clean (although Go's love of shadowing cause subtle).
In my opinion, we need a syntax that is similar to a "catch" block in other languages, but easier. Perhaps something like this:
v := getName() check err: {
return errors.Wrap(err, "could not get name")
}
This allows you to handle the error and augment it, while not introducing anything magical. It's exactly equivalent to an "if v, err :=", but without introducing a new scope and not polluting the current scope with an error variable. This syntax would happily support fallthrough: v := getName() check err: {
log.Printf("could not get name, ignoring: %s", err)
}
// v is now the zero value
And of course you could still support a syntax for introducing a new scope: if v := getName() {
// v is now valid
} check err: {
// You can return or anything else
}
You could easily extend it to error types with some kind of matching syntax: v := getName() check err == io.EOF {
// On EOF
} check err: {
// All other errors
}
The above syntaxes don't support chaining. I'm on the fence. I like Rust's "?" postfix syntax, and I think it could work: // This could be "monadic"; the first error short-circuits
ceo := getPerson()?.getCompany()?.getCEO() check err: {
return errors.Wrap(err, "couldn't get CEO")
}
But why not just let "." be smart about errors and fall through like this? ceo := getPerson().getCompany().getCEO() check err: {
return errors.Wrap(err, "couldn't get CEO")
}
After all, "." can know if the function returns multiple values, and "." on a tuple (or whatever Go calls it) isn't valid, so why not "promote" the "." to a high-level operator here?The awkwardness of the try proposal goes deeper than just error handling, too, I think. One reason Go can't solve its error handling problem elegantly is because of its reliance of multiple, exclusive return types. Almost all functions with this signature:
func getName() (string, error)
...obey the unwritten rule that the function returns either a valid value, or an error. If you get an error, the value is supposed to be unusable, and the way to check for it is to look at whether there was an error.†In many type systems, a situation where a return value can be either A or B is variously called a union, or discriminated union, or enum, or sum type, which is the term I prefer. It's always bugged me that Go's designers didn't go one step further and made sum types a first-class citizen, because I think it would fit Go rather nicely. TypeScript solves it this way:
function getName(): string | number
And you can also define types this way: type number = int | float64
This, incidentally, introduces the idea of optional values: function takesOptional(x: string | null)
Back to error handling, it would be more natural for a function to declare itself this way: func getName() string | error
After all, it returns a value or an error. It can never be the superposition of both.In this regime, anything that gets a value needs to explicitly check for what it is. "switch" on type would work, just like today, but that gets verbose for mere errors. So we just say that the "check" syntax as outlined above would work for any union that involves an error. In other words:
func getThing() Person | Company | error {
...
}
thing := getThing() check err: {
return errors.Wrap(err, "can't get thing")
}
We can do this because we can say that "error" is special and known to the compiler, just like make() etc. are special.Of course, sum types go beyond errors, and open other avenues that are very poorly served by Go right now.
---
† This, unfortunately, isn't universally true. For example, io.Reader's Write() method's contract says that if it returns io.EOF, it may still have read a final amount of data into its buffer. Many get this wrong and ignore the data read. Which points to the problem of conventions that only seem like unwritten rules, but also highlights how the lack of strong type-system support creates the issue in the first place.
Error handling in go is not concise, and calling it explicit is in insult to anyone with a modicum of abstract reasoning skills. Error handling in go is not explicit, it's verbose. Error handling in go is not concise, it's broad. Error handling in Go is not consistent, it's an exercise left up to diligent programmers.
As golang's code base grows, you're going to see this mistake play out over and over and over again.
Having a Result<T> construct would have been great for go.
If you don't like writing `if err!=nil {...}` throughout your code base surely you can just create some middleware function in its own package that has switch statements based on error cases. Checking for errors frequently in the running of the code is more or less a Good Thing.
Most of the time the receiver is swallowing the error or spitting it to stdout, so why bother
So you can do (sans syntax):
ErrorCheckerFunc(fn myParams -> MyFunc(myParams), "message")
ErrorCheckerFunc(fn myParams2 -> MyFunc2(myParams2), "message2")
etc...and then the actual function:
ErrorCheckerFunc(fn myFunc, message){
returnVal, returnError = myFunc();
switchError:
case error is foo:
print error
case error is bar:
log error print "error logged"
...
case n+1 etc
// you can handle message in a similar way to get
// cases by function names, and if you have elixir
// style quote unquote metaprogramming in Golang you might just be able to get function names based on passed function - I don't think this is in the language spec though it may be possible to do some other way.
if error not nil do switchError(error)
return RuhRoh
else
return returnVal
}
It's not so bad, it's just a middleware.Or maybe she took the approach Linus did with git and just let it crap out and start clean next big bang.