Go by Example

Custom Errors

Implementing the error interface with a struct to carry structured context callers can extract.

A custom error is a Go type with an Error() string method, a function attached to a type that provides its message. Use a struct, a value that groups named fields, when callers need details such as an operation or file name.

Return the custom type as an error. Callers use errors.As to find that type and read its fields. An Unwrap method returns the earlier error that caused this one.

package main
 
import (
    "errors"
    "fmt"
)
 
var ErrUnavailable = errors.New("service unavailable")
 
type RequestError struct {
    Method string
    URL    string
    Cause  error
}
 
func (e *RequestError) Error() string {
    return fmt.Sprintf("%s %s: %v", e.Method, e.URL, e.Cause)
}
 
func (e *RequestError) Unwrap() error {
    return e.Cause
}
 
func fetch(url string) error {
    return &RequestError{Method: "GET", URL: url, Cause: ErrUnavailable}
}
 
func main() {
    err := fetch("/users/99")
    var requestErr *RequestError
    if errors.As(err, &requestErr) {
        fmt.Println(requestErr.Method, requestErr.URL)
    }
    fmt.Println(errors.Is(err, ErrUnavailable))
}

In production

Returning an error value lets the function change its custom error type later while callers keep using the same result. Add Unwrap() error when the custom error contains an earlier cause. Treat the message as text for people, not as a fixed format for other code to parse.

Enjoyed this? Get more software craft delivered to your inbox.