error — Go interface for expected failures. Exception — not in Go (use panic/recover).
Error interface:
1type error interface {2 Error() string3}
Creating errors:
1var ErrNotFound = errors.New("not found")23type ValidationError struct {4 Field, Message string5}67func (e *ValidationError) Error() string {8 return fmt.Sprintf("%s: %s", e.Field, e.Message)9}1011func load(path string) (*Config, error) {12 data, err := os.ReadFile(path)13 if err != nil {14 return nil, fmt.Errorf("loading %s: %w", path, err)15 }16 // ...17}
Error handling:
1if errors.Is(err, ErrNotFound) {2 // handle3}45var valErr *ValidationError6if errors.As(err, &valErr) {7 fmt.Println(valErr.Field)8}
Go philosophy:
Common mistakes:
== instead of errors.Is().