Custom error types
A custom error type is any type you define that has an Error() string method. You reach for one when the caller needs structured facts about the failure, not a sentence.
Detailed Explanation
In Go, error is an ordinary interface with one method:
type error interface {
Error() string
}
Anything with that method is an error. That is the whole contract. Interface satisfaction in Go is implicit, so you never declare "implements error" — you write the method and the type is an error.
Why define your own. errors.New("bad email") gives the caller a string. Strings are fine for logging and terrible for decisions. Say you are validating a signup form and the HTTP layer needs to return {"field": "email", "message": "..."}. With a string, the handler has to parse English. With a custom type carrying a Field field, the handler reads ve.Field. The rule of thumb: define a type when the caller must act on something inside the error. If the caller will only log it, a wrapped string error is enough.
How the caller gets it back. Use errors.As. You pass a pointer to a variable of your concrete type; errors.As walks the error chain and, if it finds a match, assigns it and returns true. Its sibling errors.Is compares against a sentinel value instead. Both are chain-aware, which is what makes them better than a bare type assertion.
Unwrap makes the chain work. Deep code returns a low-level error. Middle layers add context. If your type stores the cause and exposes Unwrap() error, then errors.Is and errors.As can see straight through your type to whatever is underneath. Without Unwrap, your type is a wall: the original cause is invisible to every caller above you.
Pointer receivers are the convention. Declare func (e *ValidationError) Error() string, not a value receiver. Two reasons. Error values often carry a cause and are not cheap to copy. More importantly, with a pointer receiver only *ValidationError satisfies error, so two distinct errors are never accidentally equal by field comparison.
The typed-nil trap. An interface value has two parts: a type and a value. It is nil only when both are empty. If you declare var e *ValidationError, leave it nil, and return e from a function whose return type is error, the caller's err != nil is true. The interface holds the type *ValidationError and a nil pointer. Always return a literal nil, and never declare a function that returns your concrete error type.
What it costs. Every custom error type is public API. Callers will type-switch on it, so changing or removing it is a breaking change. Start with fmt.Errorf and %w; promote to a type only when someone actually needs the fields.
Code Examples
package main
import (
"errors"
"fmt"
)
// ErrEmpty is a sentinel: a fixed value callers can compare against.
var ErrEmpty = errors.New("value is empty")
// ValidationError carries the field that failed, so an HTTP handler can
// build a per-field response instead of parsing an error string.
type ValidationError struct {
Field string
Msg string
Err error // the underlying cause, if there is one
}
// Error is the only method the error interface requires.
// The pointer receiver means *ValidationError is the error type, not the value.
func (e *ValidationError) Error() string {
return fmt.Sprintf("field %q: %s", e.Field, e.Msg)
}
// Unwrap lets errors.Is and errors.As see past this type to the cause.
func (e *ValidationError) Unwrap() error { return e.Err }
func validateUsername(name string) error {
if name == "" {
return &ValidationError{Field: "username", Msg: "must not be empty", Err: ErrEmpty}
}
return nil
}
func main() {
err := validateUsername("")
// errors.As walks the chain and fills in your concrete type.
var ve *ValidationError
if errors.As(err, &ve) {
fmt.Println(ve.Field) // username
}
// errors.Is walks the same chain looking for a sentinel value.
fmt.Println(errors.Is(err, ErrEmpty)) // true
// The Error() method is what fmt and log print.
fmt.Println(err) // field "username": must not be empty
}The typed-nil trap, using the ValidationError above.
// The typed-nil trap, using the ValidationError above.
// Broken: the return type is error, but we return a concrete pointer.
func brokenCheck(id int) error {
var e *ValidationError
if id < 0 {
e = &ValidationError{Field: "id", Msg: "must be positive"}
}
// Even when e is nil, the interface carries the type *ValidationError,
// so the caller's err != nil is true.
return e
}
// Fixed: return an untyped nil on the success path.
func fixedCheck(id int) error {
if id < 0 {
return &ValidationError{Field: "id", Msg: "must be positive"}
}
return nil
}Common Gotchas
A nil concrete pointer is not a nil error
returning a nil `*MyError` from a function declared to return `error` produces a non-nil interface. Return a literal `nil` instead, and never give a function a concrete error return type.
No Unwrap means no chain
if your type stores a cause but does not expose `Unwrap() error`, `errors.Is` and `errors.As` stop at your type and the real cause becomes unreachable.
Type-switching on errors freezes your API
once callers assert on `*ValidationError`, renaming it or changing its fields breaks them. Keep the exported surface of an error type small.
Prefer `%w` before a new type
`fmt.Errorf("loading config: %w", err)` adds context and keeps the chain intact. Define a type only when the caller needs the structured fields.