Ruby, what exception is best to handle disabled environment variables?

script I wrote spaces at startup and requires the environment variable to be set, but which of the Ruby Exceptions is better? I used LoadError , I just want to be as descriptive as possible and follow the appropriate conventions.

Secondly, I can’t find another way to check if the environment variable is set, except for checking the length, but this does not 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 
+6
source share
4 answers

According to the documentation for LoadError , which should be used when the problem "requires" has a problem. I think a more proper method would be to subclass StandardError and make one that suits you. If that seems a bit, I would just go with a StandardError with a descriptive message.

+6
source

You can do something like:

 ENV['SECRET_KEY_XXYY'] || raise('no SECRET_KEY_XXYY provided') 
+12
source

Creating 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 an exception in this block of code may not be acceptable in this case, because it seems that you are simply printing a message with it. As a rule, never raise an exception if you are not ready to end it. In other words, avoid using exceptions for expected conditions. If the program can continue without installing FOO, it would be better to just make the execution of the system operator conditional:

 system("open http://example.com/" + ENV['FOO']) if ENV['FOO'] 

or

 ENV['FOO'] && system("open http://example.com/" + ENV['FOO']) 
+2
source

Here is a list of exception types at http://bugs.ruby-lang.org/projects/ruby/wiki/ExceptionClassesDoc

I would choose ArgumentError since you are saying that the value of ENV['FOO'] is not what you expected.

+2
source

Source: https://habr.com/ru/post/922652/


All Articles