IntermediateLesson 9 of 15
Errors as Values – Go
error returns, wrapping with %w, and errors.Is and errors.As.
Go has no exceptions. Functions that can fail return an error as their last value; nil means success. The caller checks explicitly – the famous if err != nil. This is verbose, but it makes the error path visible in the code.
package main
import (
"fmt"
"strconv"
)
func main() {
n, err := strconv.Atoi("abc")
if err != nil {
fmt.Println("Error:", err) // Error: strconv.Atoi: parsing "abc": invalid syntax
return
}
fmt.Println(n)
}With fmt.Errorf("...: %w", err) you wrap an error with context without losing the cause. errors.Is checks whether a particular error is in the chain. Predefined errors are usually named ErrXyz (sentinel errors).
package main
import (
"errors"
"fmt"
)
var ErrNichtGefunden = errors.New("not found")
func suche(id int) (string, error) {
if id != 1 {
return "", fmt.Errorf("search %d: %w", id, ErrNichtGefunden)
}
return "Ada", nil
}
func main() {
_, err := suche(7)
fmt.Println(err) // search 7: not found
fmt.Println(errors.Is(err, ErrNichtGefunden)) // true
fmt.Println(err == ErrNichtGefunden) // false
}For structured errors you define your own type with Error() string. errors.As searches the chain for this type and gives you access to its fields:
package main
import (
"errors"
"fmt"
)
type ValidierungsFehler struct{ Feld string }
func (e *ValidierungsFehler) Error() string {
return "invalid field: " + e.Feld
}
func pruefe(name string) error {
if name == "" {
return &ValidierungsFehler{Feld: "name"}
}
return nil
}
func main() {
err := fmt.Errorf("save: %w", pruefe(""))
fmt.Println(err) // save: invalid field: name
var ve *ValidierungsFehler
if errors.As(err, &ve) {
fmt.Println("Field:", ve.Feld) // Field: name
}
}TipError messages start lowercase and end without punctuation ("file not found") so that they chain together cleanly when wrapped.
errors.Join (Go 1.20) combines several errors.WarningDo not silently ignore errors with
_ unless you have a good reason. Compare errors with errors.Is/errors.As, not with == – as soon as someone wraps with %w, == fails.