Errors Cheatsheet

The Error Interface

type error interface {
    Error() string
}

Basic Handling

result, err := someFunction()
if err != nil {
    // 1. Handle (log, retry, etc)
    // 2. Return (propagate)
    return err 
}

Creating Errors

  • Simple: errors.New("message")
  • Formatted: fmt.Errorf("error code: %d", code)
  • Wrapped: fmt.Errorf("context: %w", err)

Custom Errors

type MyError struct {
    Code int
}
func (e MyError) Error() string {
    return fmt.Sprintf("Error %d occurred", e.Code)
}

Comparison

  • Use errors.Is(err, target) to check if an error is a specific value.
  • Use errors.As(err, &target) to cast an error to a specific type.

Key Rules

  • Return error as the last value.
  • Return zero values along with a non-nil error.
  • Avoid panic/recover for normal control flow.
  • Success is represented by nil.