error — a Go interface type representing expected failures. Exception — a concept from other languages (Java/C++) not directly present in Go (Go uses panic/recover instead).
The error interface:
1type error interface {2 Error() string3}
Any type with Error() string method implements this interface.
Error creation patterns:
1// Simple errors2var ErrNotFound = errors.New("not found")3var ErrPermission = errors.New("permission denied")45// Custom error types6type APIError struct {7 StatusCode int8 Message string9}1011func (e *APIError) Error() string {12 return fmt.Sprintf("API error %d: %s", e.StatusCode, e.Message)13}1415// Error wrapping (Go 1.13+)16func fetchData(url string) ([]byte, error) {17 resp, err := http.Get(url)18 if err != nil {19 return nil, fmt.Errorf("fetching %s: %w", url, err)20 }21 defer resp.Body.Close()22 return io.ReadAll(resp.Body)23}
Error handling:
1// Direct comparison2if err == ErrNotFound {3 // handle4}56// Wrapped error comparison7if errors.Is(err, ErrNotFound) {8 // works with wrapped errors9}1011// Type assertion for custom errors12var apiErr *APIError13if errors.As(err, &apiErr) {14 fmt.Println(apiErr.StatusCode)15}
Go philosophy:
Common mistakes:
== instead of errors.Is() for comparison.panic where error return is appropriate.