Search code examples
rubyshellenvironment

Ruby, which exception is best to handle unset environment variables?


The script I wrote runs at start up and requires that an environment variable be set, but which of Ruby's Exceptions, is best? I used LoadError, I just want to be as descriptive as possible and follow the proper conventions.

Secondly, I can't find another way to see if an environment variable is set besides checking it's length, but that doesn't seem so elegant.

begin
  raise LoadError if ENV['FOO'].to_s.length == 0
  system "open http://example.com/" + ENV['FOO']
rescue Exception => e
  puts "=> #{e} FOO environment variable not set"
end

Solution

  • Could use ENV.fetch('FOO') which then raises a KeyError if not found.