Error handling in Go(lang). Whats about it?

Merten van Gerven
2 min readMar 5, 2016

--

Up to now I’ve been a quiet observer and learner of the go(lang) ways since my introduction to it and all its wonderful possibilities almost a year ago, so hopefully my first posting on the topic doesn’t cause too many brain explosions and fits at the mere thought of some of my ideas.

My intention is to throw this juicy morsel of an idea to you (the go community) in order to spark a discussion and get feedback from your welcomed responses. So without further ado, let me jump into the meat of it.

After working with go for almost a year (and loving it) I’m still looking for ways to make my coding more legible, simple, dry, and when possible aesthetically pleasing. I intermittently come across code that represents a slippery stairway to hell copied multiple time over into various parts of an application or worse, an incoherent jumble of what probably would make a pretty decent word-search puzzle. This is something I endeavor to avoid at all costs. I can’t help but feel that the continuously repeated (albeit idiomatic)

if err != nil {
return
}

plays a small role in making the code flow a little less easily. Granted, it’s legible and simple but not entirely dry imho. So this got me thinking about ways this could be coded that makes it a little less wet while still following the original objective of being legible, simple, dry, and for the cherry on the cake, aesthetically pleasing.

Enter, Work.

or a slightly different alternative where with a still simpler Task implementation might be

however I think the first alternative may be a little more idiomatic than the second.

My own opinion is that this construct is still legible, simple and dry enough to be of some use while also having several other possible advantages;

  • individual tasks could be wrapped to allow injection of needed resources or other parameters
  • A complete work list could be created before any execution of tasks are executed allowing for other initialization/validation to be performed before running tasks that could change state, a sort of transaction if you will.
  • Maybe some others I haven’t thought of …

So now I put it to you, the dear go(lang) community. Whats about it? Please comment at your leisure. Thanks.

p.s. No offense intended by the “whats about it?” reference from the journalist asking Leo DiCaprio about his “first oscars”. https://www.youtube.com/watch?v=nWtWdBLiBDY

--

--