Go Error Handling (Part 1) — Errors as Values

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




Blogger at codingbee.net

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

I made some spaghetti (not the edible kind)

Appcode 2019 1 1 — Objective C Ide For Developers


Generating mock data with Mimesis: Part II

How to automatically monitor Instagram Hashtags for free with a Google Sheets Script

Github Personal Access Token

How to root Alcatel One Touch Pixi 3 4009d


Weekly Update Q4/01

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
Sher Chowdhury

Sher Chowdhury

Blogger at codingbee.net

More from Medium

Druid complex Lookup using other dimensions, with native query or Golang

MySQL: Init GORM from YAML with rk-boot

Concurrency in Golang

Go modules in mono-repo