Custom error types
- Version
- 1.27
- Review
- Draft
Summary#
Any type with an Error() string method is an error. Use errors.New for a fixed condition and a custom type when callers need details. errors.AsType retrieves that type from a wrapped error.
Syntax#
var ErrEmpty = errors.New("value is empty")
func (e *FieldError) Error() string
fieldErr, ok := errors.AsType[*FieldError](err)
Example#
package main
import (
"errors"
"fmt"
)
var errEmpty = errors.New("value is empty")
type fieldError struct {
field string
cause error
}
func (e *fieldError) Error() string { return e.field + ": " + e.cause.Error() }
func (e *fieldError) Unwrap() error { return e.cause }
func require(field, value string) error {
if value == "" {
return &fieldError{field: field, cause: errEmpty}
}
return nil
}
func main() {
err := fmt.Errorf("sign up: %w", require("email", ""))
fmt.Println(err)
if target, ok := errors.AsType[*fieldError](err); ok {
fmt.Println("fix field:", target.field)
}
fmt.Println(errors.Is(err, errEmpty))
fmt.Println(errors.Is(err, errors.New("value is empty")))
fmt.Println(require("email", "lan@example.com") == nil)
}
Expected output#
sign up: email: value is empty
fix field: email
true
false
true
Common mistakes#
Each errors.New call returns a distinct value, even for the same text. Declare a sentinel once and reuse it. Return literal nil on success. Returning a nil *fieldError variable as error yields a non-nil interface.
Version applicability#
Custom error types and errors.New work from Go 1.0. %w, errors.Is and errors.As arrived in Go 1.13. The example requires Go 1.26 for errors.AsType. Use errors.As with a target variable on Go 1.13 through 1.25.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0