How to Use errors.New and fmt.Errorf in Go

Use errors.New for static messages and fmt.Errorf for formatted or wrapped errors with context.

Use errors.New for simple, static error messages and fmt.Errorf when you need to format variables or wrap existing errors with context.

// Simple static error
var ErrNotFound = errors.New("item not found")

// Formatted error with context
func processFile(path string) error {
    if _, err := os.Stat(path); err != nil {
        return fmt.Errorf("failed to access %s: %w", path, err)
    }
    return nil
}