Go

Custom Error Type with Fields

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Implement the `error` interface (`Error() string`) on your own type to carry structured data. Pair with `errors.As` so callers can extract the fields.
Go
Raw
package main

import (
    "errors"
    "fmt"
)

type ValidationError struct {
    Field   string
    Message string
}

func (e *ValidationError) Error() string {
    return fmt.Sprintf("invalid %s: %s", e.Field, e.Message)
}

func validate(name string) error {
    if name == "" {
        return &ValidationError{Field: "name", Message: "cannot be empty"}
    }
    if len(name) > 50 {
        return &ValidationError{Field: "name", Message: "too long"}
    }
    return nil
}

func main() {
    err := validate("")
    fmt.Println(err)                                     // invalid name: cannot be empty

    var ve *ValidationError
    if errors.As(err, &ve) {
        fmt.Printf("field=%s reason=%s\n", ve.Field, ve.Message)
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.