Introducing Radical.sh

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

Custom Exception in Go

Most of the time errors.New method can be used to create an exception in Go. But sometimes the custom exceptions need to have custom field apart from string field for example http status code and other parameters. Custom exception can be created in Go by implementing in Error interface.

Complete example for a custom exception. This example also uses As method to check and convert the error to custom error so that fields from the custom error can be accessed.

package main

import (
    "errors"
    "fmt"
)

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

    var _, error = car.getMileage()
    var customException *CustomException

    if errors.As(error, &customException) {
        fmt.Printf("in custom exception %s %+v", customException.customMessage, error)
    } else {
        println("in generic exception")
    }
}

type CustomException struct {
    customMessage string
}

func (customException CustomException) Error() string {
    return "CustomException"
}

type Car struct {
    name string
}

func (car Car) getMileage() (int, error) {
    var myException = CustomException{}
    myException.customMessage = "Omg"
    return -1, &myException
}



Output
in custom exception Omg CustomException