Category Archives: go

Send error events using defer statements in Go

Note: In my current job I code in Go, after a long, long time primarily using Java. So I’m still learning Go, through the prism of Java experience. I might write once in a while about it … like this.


Suppose you’ve got a big old function that returns an error if there’s trouble. Commonly, you’d log the error if it comes back.

err := bigOldFunc(input)
if err != nil {
  log.Errorf("Oh no: %v", err)
}

Another option could be to send an event about the error to a collection system. That’s like logging, but the event could store structured details about the context of the call beyond the error string. (Sorry if my indentation isn’t right.)

err := bigOldFunc(input)
if err != nil {
  analytics.SendEvent(analytics.Event{
    Message:    "Oh no",
    Properties: analytics.NewProperties()
      .Set("input", input)
      .Set("error", err.Error()),
    },
  )
}

What if you want the event to include more about what the function was doing at the time? For example, suppose the function was looping through a list, and you’d like the include the current item in the event. You don’t know that by the time the function has returned.

Continue reading