Go Error Handling (Part 1) — Errors as Values

Sher Chowdhury
2 min readDec 28, 2020

--

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 try...catch 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 error 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 nil 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.

err = foo()
if err != nil {
// Something unexpected occurred
return err
}

Let’s assume for now that the foo() function returns a single return value of the type error. In that case, this error return value acts as an indicator on whether the foo() 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 try...catch 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 errors 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. foo(), 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

--

--

Sher Chowdhury
Sher Chowdhury

Written by Sher Chowdhury

Software Engineer based in the UK

No responses yet