error — Go interface for expected failures. Exception — not in Go.
Error interface:
1type error interface {2 Error() string3}
Creating errors:
1var ErrNotFound = errors.New("not found")23type APIError struct {4 Code int5 Msg string6}78func (e *APIError) Error() string {9 return fmt.Sprintf("error %d: %s", e.Code, e.Msg)10}
Error handling:
1if errors.Is(err, ErrNotFound) {2 // handle3}45var apiErr *APIError6if errors.As(err, &apiErr) {7 fmt.Println(apiErr.Code)8}
Common mistakes:
== instead of errors.Is().