5.6 Best Practices

Key points about error handling

Writing Good Error Messages

Effective error messages help developers and users understand what went wrong and how to fix it. Here are guidelines for writing good error messages:

1. Be specific and contextual

Bad:

return errors.New("error")

Good:

return fmt.Errorf("failed to read config file %q: %w", filename, err)

2. Include relevant values

Bad:

return errors.New("invalid value")

Good:

return fmt.Errorf("age must be between 0 and 150, got %d", age)

3. Use consistent formatting

Use lowercase for error messages (unless starting with proper nouns or acronyms), and don't end with punctuation:

// Good
errors.New("file not found")
errors.New("invalid user ID")
errors.New("database connection failed")

// Avoid
errors.New("File not found!")
errors.New("Invalid User ID.")

4. Start with the operation that failed

Good error messages tell a story from the top level down:

// Good: tells the story
return fmt.Errorf("failed to process user %d: %w", userID, err)

// Less clear
return fmt.Errorf("error: %v", err)

5. Don't leak implementation details

Bad:

return fmt.Errorf("sql: no rows in result set")

Good:

return fmt.Errorf("user with ID %d not found", userID)

6. Make errors actionable when possible

// Good: tells user what to do
return fmt.Errorf("config file %q not found: create it or set CONFIG_PATH environment variable", path)

// Less helpful
return fmt.Errorf("config file not found")

Error handling checklist