In any programming language, it’s sometimes necessary to handle a custom error type and handle it in a custom way.
In Go, you can create a specific type that implements the “error” interface, so that when that error type is received, it can be recognized using the type assertion system. Here’s a practical example:
type CustomError struct {
Inner error
}
func (e CustomError) Error() string {
return fmt.Sprintf("this is a custom error due to: %s", e.Inner.Error())
}
to check the if returned error is a CustomError
if returnedError, isCustomError := err.(CustomError); isCustomError {
...
}
otherwise (from go 1.13)
var got CustomError
isCustomError := errors.As(err, &got)
if !isCustomError {
...
}