Go Error Handling (Part 1) — Errors as Values

Image for post
Image for post
Photo by Erik Mclean on Unsplash

When something unexpected occurs, then you want your app to raise that as an error and then perform some follow on tasks to address that error, aka error handling. Raising errors and error handling are common traits in well-written programs.

This article is part of the Error Handling in Go series.

In a lot of modern programming languages, raising errors + error-handling is done with something like a construct, however that construct doesn’t exist in Go. Instead, Go takes an errors as values approach. This approach involves capturing errors into variables using Go’s built-in type. In other words, we can create “error variables”, similar to how we create variables of other types, such as integer variables and string variables.

The error variable holds a value of when there are no errors. If it holds anything else, then it means we have an error. Based on this concept, it means that we can implement error-handling with a simple if-statement.

This error return value acts as an indicator on whether the function ran successfully, and the subsequent if-statement is how we trigger the error-handling code-block if we get an error. This is Go’s equivalent of the construct, and you’ll see this pattern (or variations of it) popping up all over the place. Here’s a quick example of this pattern in action (lines 20–24 and 27–31).

We’re also using the package (line 4) for creating the error variables (line 14). This is just an early preview, and we’ll cover this example in more detail in Go Error Handling (Part 3) — The errors Package

It’s best practice for Go functions, e.g. , to return an error value for one of its output parameters. We then place an if-statement immediately after a function call to check its return value.

Further reading

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