Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Exception type check in golang in Go

Is method is available in errors package can be used to check the whether error is of type 'myException' or any custom exception which can return true for boolean check on Is(target error) method.

package main

import (
    "errors"
    "fmt"
)

func main() {
    var car = Car{}
    car.name = "Audi"

    var _, error = car.getMileage()

    if errors.Is(error, myException) {
        fmt.Printf("in custom exception %+v", error)
    } else {
        println("in generic exception")
    }
}

type Car struct {
    name string
}

var myException = errors.New("unable to compute mileage")

func (car Car) getMileage() (int, error) {
    return -1, myException
}


Output of this program would be
in custom exception unable to compute mileage