I was not very familiar with checking an error’s type in Golang, so I spent a few minutes learning about it today. It turns out that it’s incredibly easy to do.

Running the below code shows the output: 2009/11/10 23:00:00 got custom error: err1

package main

import (
    "errors"
    "log"
)

var (
    customErr = errors.New("err1") // create a error, identified by its var name
)

// oops always returns our custom error. Oops!
func oops() error {
    return customErr
}

func main() {
    err := oops()
    if errors.Is(err, customErr) {  // check error type with errors.Is()
        log.Fatal("got custom error: ", err)
    }
}

This is doing more than just matching the string of the error, as this does not show any output:

package main

import (
    "errors"
    "log"
)

func oops() error {
    return errors.New("err1")
}

func main() {
    err := oops()
    if errors.Is(err, errors.New("err1")) {
        log.Fatal("got custom error: ", err)
    }
}