Error Handling in Go

Mastering pragmatic error handling in your Go code


First thing’s first: Errors in Go are not Exceptions. Dave Cheney wrote an epic blog post about it, so I’ll refer you to it and summarise: In other languages, you are uncertain if a function may throw an exception or not. Instead of throwing exceptions, Go functions support multiple return values, and by convention, this ability is commonly used to return the function’s result along with an error variable.

result can’t be trusted before checking for errors
The blank identifier is dark and full of terrors.

Under the hood

The error Interface

Under the hood, the error type is a simple single method interface, and if you’re not familiar with it, I highly recommend going over this post in the official Go Blog.

error interface from the source code

The built-in errorString struct

The most commonly used and widespread implementation of the error interface is the built-in errorString struct. It is the leanest implementation you can think of.

source: Go source code
try it

Another simple example is the pkg/errors package. Not to be confused with the built-in errors package you learned about earlier, this package provides additional important capabilities such as error wrapping, unwrapping, formatting and stack trace recording. You can install the package by running go get .

Working with Errors

Type Assertion

Type Assertion serves a great role when working with errors. You’ll use them to assert information out of an interface value, and since error handling deals with custom implementations of the error interface, performing assertions on errors is a very handy tool.

playground: short syntax panic, safe long syntax

Asserting with interface type T

Performing type assertion x.(T) with an interface typeT asserts that x implements the T interface. This way you can guarantee an interface value implements an interface and only if it does, you will be able use its methods.

source: pkg/errors

Asserting with concrete type T & Type Switches

I will preface this section by introducing two similar error handling patterns that suffer from a couple of drawbacks and pitfalls. It doesn’t mean they’re not common, though. Both of them can be handy tools in small projects, but they don’t scale well.

Wrapping up

That’s it! You’re now familiar with errors and should be ready to tackle any errors your Go app may throw (or actually return) your way!

What’s next?

Go’s error handling is a very hot topic these days. Now that you’ve got the basics, you may be interested in what the future holds in store for Go’s error handling!

Back End Developer and Golang Enthusiast. I am a sucker for great code, and I like to hack whatever comes my way.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store