Custom Errors and errors.As
errors.Is matches identity — is this error that sentinel? errors.As matches structure — is this error (or anything it wraps) of this type? The difference matters when you need data out of the error, not just a yes/no.
The limit of sentinels
var ErrNotFound = errors.New("not found")
// caller knows it's not found, but which ID?
return ErrNotFound // data lostSentinels are identity tags. They carry no payload. When the error needs context — which field failed, what value was rejected, which ID was missing — a sentinel is the wrong tool.
Custom error types
type ValidationError struct {
Field string
Message string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("%s: %s", e.Field, e.Message)
}Any type with an Error() string method satisfies error. Adding fields makes the error a structured value, not a string.
errors.As — type extraction through the chain
var ve *ValidationError
if errors.As(err, &ve) {
fmt.Println("bad field:", ve.Field)
}errors.As walks the unwrap chain looking for an error assignable to *ValidationError. On match it fills ve and returns true. It works through any number of %w wraps:
err := fmt.Errorf("create ticket: %w", &ValidationError{"title", "empty"})
var ve *ValidationError
errors.As(err, &ve) // true — unwraps one layerIs vs As — decision rule
- Known sentinel, branch on which one →
errors.Is - Structured error, need fields →
errors.As - Both in the same error chain: both work simultaneously
Hint
Define ValidationError with Field and Message string fields. Make Error() format them with fmt.Sprintf. In NewTicket, return a *ValidationError (wrapped with %w in fmt.Errorf) when title or description is empty. In ExtractField, call errors.As targeting *ValidationError and return its Field.
Task
In validate.go:
- Add
Field stringandMessage stringfields toValidationError; implementError() stringto return"<Field>: <Message>". - Complete
NewTicket(title, description string) (Ticket, error)— return a*ValidationError(wrapped withfmt.Errorf("new ticket: %w", ...)) whentitleis empty (field="title") ordescriptionis empty (field="description"). Otherwise return a validTicket. - Complete
ExtractField(err error) (string, bool)— useerrors.Asto extract theFieldfrom a*ValidationErroranywhere in the error chain.
Check
go test ./exercises/05_ticket_v2/06_errors_as/ -vSource: exercises/05_ticket_v2/06_errors_as/README.md · Inspired by Mainmatter’s 100 Exercises to Learn Rust (CC BY-NC 4.0) — all Go prose here is original, free for non-commercial use.