« previous

Go Errors Part 1

… it is clear that these Go programmers miss a fundamental point about errors: Errors are values. - Rob Pike

This takes a while to get use to when moving to Go but if you get anything out of what I am about to write, it would be that quote. Let me go into more detail. Errors are values and is an interface.

// builtin/builtin.go L252

// The error built-in interface type is the conventional interface for
// representing an error condition, with the nil value representing no error.
type error interface {
	Error() string

So what does this mean? Lets use the following code for example:

type CustomError struct {
	Message string

func (e CustomError) Error() string {
	return e.Message

If you are unfamiliar with Go’s interface type, essentially they are close to Java interfaces but with a Go flare. So you can pass it around like it was a normal error. Why is this useful? Well, for example, you could add a stack-trace to each error. That is helpful when you need the stack passed back for internal tools. I don’t recommend sending stack traces in public facing API but hey, thats just me.

So make errors useful and in part 2, I will show you how to capture stack traces.

comments powered by Disqus