error — a Go interface for expected failures (value-based). Exception — not a Go concept (Java/C++ use try-catch; Go uses panic/recover).
The error interface:
1type error interface {2 Error() string3}
Any type with Error() string method implements this interface.
Error creation patterns:
1// Sentinel errors2var ErrNotFound = errors.New("not found")34// Custom error types5type APIError struct {6 Code int7 Message string8}910func (e *APIError) Error() string {11 return fmt.Sprintf("api error %d: %s", e.Code, e.Message)12}1314// Wrapping errors15func fetch(url string) ([]byte, error) {16 resp, err := http.Get(url)17 if err != nil {18 return nil, fmt.Errorf("fetching %s: %w", url, err)19 }20 defer resp.Body.Close()21 return io.ReadAll(resp.Body)22}
Error handling:
1// errors.Is for sentinel errors2if errors.Is(err, ErrNotFound) {3 // handle4}56// errors.As for custom errors7var apiErr *APIError8if errors.As(err, &apiErr) {9 fmt.Println(apiErr.Code)10}
Go philosophy:
Common mistakes:
== instead of errors.Is().