dimanche 4 octobre 2020

Less error handling noice in GO: CombineErrors


TDLR; A nice trick to greatly reduce error handling in Go code.



Error handling in go can easily get in the way of readability in Go. Big time! Reducing the verbosity of error handling and in particular the amount of if-statements that invade our application code has been occupying my thoughts for a few months now.  
I’m appalled that it’s so difficult to find good tricks on this. The go blog has very little information on this. Let's face it I risk GOing nuts!


Some time ago I realised that some errors don’t have to be handled immediately. Postponing error handling opens up a few possibilities. The first and foremost is CombiningErrors. But let’s first look at the problem. Here’s a bit of typical code for obtaining data from somewhere.



Now that’s a short example but imagine this constructor taking a few more arguments.


In this case we’re producing 3 errors. What if we could just combine those three into a single error, that will be nil if all sub-errors are nil, then we could return only one function. Something like 



This combining function seems like generic code so there’s probably a library out there doing the job. Indeed there is, for instance https://godoc.org/go.uber.org/multierr and https://godoc.org/github.com/hashicorp/go-multierror 


Now there’s just one small improvement to do here, one that I actually learnt from one of the posts at the go blog. There’s no need to check for a combined error with an extra if-statement. We can just return the globalErr, it'll be nil if all sub-errors are nil, and the calling function will test for errors either way.




Much better :)

Now this is a trick that won't apply in every case. Actually when does it apply? Well I'd argue that this can be used whenever there is no damage done by pursuing execution after a first error. Which in my team's code is quite often. Nice :)



Next time let’s look at another trick where we’ll transform a sequence of error generating statements into a list of functions. Let’s see how that helps.