Choose sentinel and custom errors
Choose sentinel and custom errors
A sentinel error represents a stable condition, such as a missing item. A custom error type carries structured information, such as the invalid field or permitted limit. Prefer errors.Is for stable conditions and errors.As for extracting typed details; neither requires parsing error text.
package main
import ( "errors" "fmt")
var ErrNotFound = errors.New("item not found")
func find(id int) (string, error) { if id != 1 { return "", ErrNotFound } return "pen", nil}func main() { v, err := find(1) fmt.Println(v, err == nil) _, err = find(2) fmt.Println(errors.Is(err, ErrNotFound))}The sentinel is declared once and returned for the same condition. Callers can distinguish that condition without inspecting the wording. Do not reassign an exported sentinel after initialization. Repeated errors.New calls are not equivalent to returning the same sentinel.
Expected output:
pen truetrueCarry validation details
package main
import ( "errors" "fmt")
type RangeError struct{ Value, Max int }
func (e RangeError) Error() string { return fmt.Sprintf("%d exceeds %d", e.Value, e.Max) }func check(n int) error { if n > 5 { return RangeError{n, 5} } return nil}func main() { var e RangeError err := check(8) if errors.As(err, &e) { fmt.Println(e.Value, e.Max) } fmt.Println(check(4) == nil)}The custom type exposes numeric details independent of its text. Return literal nil on success, not a typed nil pointer converted to error. Expose error types and sentinels only when callers need them; they become part of the API contract.
Expected output:
8 5trueTry it locally
Define ErrEmpty and a function first(xs []int)(int,error) returning ErrEmpty for an empty slice. Print the Is check for an empty slice and the first value of []int{9}.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Errors and cleanup 06: Choose sentinel and custom errors
Check the lesson objective before moving on.
When is a custom error type especially useful?
What should a successful error-returning function return for its error?