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
}
Use errors.New when you just need to say something went wrong with a fixed message. Use fmt.Errorf when you need to include specific details like file names or IDs, or when you want to attach a new error message to an existing one so the full history is preserved. Think of errors.New as a standard warning sign and fmt.Errorf as a detailed incident report.