Ruby Error

KeyError

KeyError is raised when accessing a hash key that doesn't exist using fetch() without a default value, or when using ENV.fetch() for missing environment variables.

Common causes

  • Using Hash#fetch with missing key and no default
  • Missing environment variable with ENV.fetch
  • Destructuring hash with missing required key
  • Using dig on nested hash with missing intermediate key

How to fix it

  • Provide a default value: hash.fetch(:key, default)
  • Use hash[:key] which returns nil for missing keys
  • Check key existence: hash.key?(:key)
  • Use fetch with block: hash.fetch(:key) { compute_default }
  • Set environment variables or provide fallbacks

Example

KeyError example
# Error example
hash = { name: "Alice" }
hash.fetch(:age)  # => KeyError: key not found: :age

# Fix with default value
hash.fetch(:age, 0)  # => 0

# Fix with block
hash.fetch(:age) { |key| "Unknown #{key}" }  # => "Unknown age"

# Or use bracket notation
hash[:age]  # => nil (no error)

Track KeyError with Checkend

Checkend automatically captures KeyError errors in your Ruby application with full context:

  • Complete backtrace with syntax highlighting
  • Request context (URL, params, headers)
  • Automatic grouping of similar errors
  • Instant notifications when errors occur

Stop debugging in production

Get full error context and fix issues faster with self-hosted error tracking.