How Generics can change error handling in Go
Important note
The generics are not yet available in Go, so this article is based only the proposal and the go2 playground.
Which means this article may be obsolete in the future.
Current error handling
Handling errors in Go creates one of the most common boilerplates in Go programming. As Go doesn’t provide try/catch (and IMO it’s a very good thing), if your function can produce errors, it will have to return 2 values which will be either the success value or the error.
Because of that, you probably encountered some kind of error handling chain like the one below which can increase your function size and may reduce readability:
This is pretty common in Go programming and it has 2 disadvantages:
- We have to check errors every time (don’t miss one).
- Most of the time, if the function encounters an error, it will just return it which makes inevitable boring error handling chains.
In Functional Programming, it exists a pattern that can help simplify this error handling. It is called the Either monad; or its subtype: the Result monad.
The Result monad consists of a structure that can contain either a type or an error. This is exactly what we need right?
Using that, you can write your function to only handle the successful case and handle the error cases in only one place. Cool isn’t it?
How we could handle errors using Generics
With the introduction of generics in Go, let’s see how we can reproduce this Monad and see how it can change the error handling in Go.
Now, our error handling chain is getting easier to manipulate:
Unfortunately, Go doesn’t allow generic type parameters for method (Why??).
But if they do, we could make it even more concise like this:
The function passed in Then() will be called only in case of Success. In case of error, it will just continue the chain.
That way, the error is checked in only one place without missing to check errors.
Conclusion
Generics will open a lot of opportunities to Go and I can’t wait to see all the possibilities it’ll create! 🚀
The Result API I created has been highly inspired by the Kotlin’s Result API (more info here: https://elizarov.medium.com/kotlin-and-exceptions-8062f589d07)
However, I’m a bit disappointed that they didn’t allow generic type parameters for methods like this one:
Also, a Void type would be very useful in some cases.
You can find the code source of this project here:
https://github.com/mbiamont/schrodingo