Skip to content

Custom Errors

Learn to create custom error types that carry structured information beyond simple strings.

Go’s error interface is simple - any type with an Error() string method satisfies it. Custom error types let you include additional context like field names, resource IDs, or error codes. This makes errors more informative and allows callers to handle different error types distinctly.

The errors.As function lets you check if an error (or any error in its chain) matches a specific type, while errors.Is checks for specific error values.

Implement two custom error types and use them in validation functions:

  1. ValidationError - Contains field name and validation message
  2. NotFoundError - Contains resource type and ID
  3. ValidateUser - Returns ValidationError for invalid inputs
  4. FindUser - Returns NotFoundError when user doesn’t exist

Custom Error Types

~15 mineasy

Implement ValidationError and NotFoundError with proper error messages

  • Custom Error Types: Implement Error() string to satisfy the error interface
  • Structured Error Data: Store additional context in error struct fields
  • Type Assertions: Use errors.As() to extract custom error details
  • Error Formatting: Use fmt.Sprintf() for consistent error messages
  • Error Handling Patterns: Different error types for different failure modes (validation vs not found)