Ruby, which exception is best to handle unset environment variables?
You can do something like:
ENV['SECRET_KEY_XXYY'] || raise('no SECRET_KEY_XXYY provided')
According to the documentation for LoadError that is supposed to be used for when a 'require' has an issue. I think the more proper method would be to subclass StandardError
and make one that fits your use. If that seems a bit much I would just go with StandardError
with a descriptive message.
Making your own exceptions is easy:
MyError = Class.new(StandardError)
raise MyError, "FOO environment variable not set" unless ENV['FOO']
system "open http://example.com/" + ENV['FOO']
Catching the exception in that code block may not be appropriate in this case, since it seems you are just printing a message with it. As a rule, never raise an exception unless you are prepared for it to terminate the program. In other words, avoid using exceptions for expected conditions. If the program can continue without FOO being set, it would be better to simply make execution of the system statement conditional:
system("open http://example.com/" + ENV['FOO']) if ENV['FOO']
or
ENV['FOO'] && system("open http://example.com/" + ENV['FOO'])