Catching Go errors with errors.Is()

Tom Deneire
3 min readApr 26, 2022
Photo by David Pupaza on Unsplash

Go error handling

Anyone who has done some development in Go will be familiar with the Go philosophy on error handling and the following pattern:

result, err := myFunc(args)
if err != nil {
// do something
}

Catching errors

As many Gophers, over time I have grown accustomed to the inevitability of Go’s errors and come to appreciate this explicit and sturdy way of handling errors. Up till recently, however, there was one aspect about Go errors that kept confusing me, namely how to catch specific errors.

Let’s look at the following example:

file, err := os.Open("myfile")
if err != nil {
// handle error
}

In a case like this, coming from a Python background, I would like to use try…catch… pattern, for instance, to create myfileshould it not exist.

In idiomatic Go there are two solutions for this.

The first is to rewrite the code to first check whether the file exists (you can use os.Stat() for that) and, if not, create it — this is probably preferable in this case.

The second is to make use of errors.Is() — this can be used if there is no workaround (see below).

errors.Is()

--

--

Tom Deneire
Tom Deneire

Written by Tom Deneire

Software engineer, technical writer, IT burnout coach @ https://tomdeneire.be/confident_coding

No responses yet