Create errors and contextual messages
Create errors and contextual messages
Use errors.New for a fixed error message and fmt.Errorf for a formatted message. Give enough context to identify the failed operation without exposing credentials or sensitive inputs. Error messages are for people; programmatic classification should use a stable error contract, not text matching.
package main
import ( "errors" "fmt")
func validate(n int) error { if n < 1 { return errors.New("quantity must be positive") } return nil}func main() { fmt.Println(validate(0)) fmt.Println(validate(2) == nil)}Each errors.New call creates a distinct error value even for identical text. A nil return means the validation succeeded. Use Error() only on a known non-nil error; fmt.Println can print error values directly.
Expected output:
quantity must be positivetrueAdd operation context
package main
import ( "errors" "fmt")
func reserve(want, stock int) error { if want > stock { return fmt.Errorf("reserve %d items: only %d available", want, stock) } return nil}func main() { fmt.Println(reserve(5, 2)) a, b := errors.New("missing"), errors.New("missing") fmt.Println(a == b)}The formatted message explains the failed operation and relevant counts. Here the numbers are synthetic and safe to display. The two missing errors have the same message but distinct identity. Do not rely on wording as an API.
Expected output:
reserve 5 items: only 2 availablefalseTry it locally
Write checkLimit(n,max int) error returning fmt.Errorf("limit %d exceeded by %d",max,n-max) when n>max. Print the error for 9,5 and whether 3,5 succeeds.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Errors and cleanup 02: Create errors and contextual messages
Check the lesson objective before moving on.
Which creates a formatted error?
Do separate errors.New calls with identical text compare equal?