<p>I'm new to Ruby, so I'm having some trouble understanding this weird exception problem I'm having. I'm using the ruby-aaws gem to access Amazon ECS: <a href="http://www.caliban.org/ruby/ruby-aws/" rel="nofollow noreferrer">http://www.caliban.org/ruby/ruby-aws/</a>. This defines a class Amazon::AWS:Error:</p>

<pre><code>module Amazon
  module AWS
    # All dynamically generated exceptions occur within this namespace.
    #
    module Error
      # An exception generator class.
      #
      class AWSError
        attr_reader :exception

        def initialize(xml)
          err_class = xml.elements['Code'].text.sub( /^AWS.*\./, '' )
          err_msg = xml.elements['Message'].text

          unless Amazon::AWS::Error.const_defined?( err_class )
            Amazon::AWS::Error.const_set( err_class,
                    Class.new( StandardError ) )
          end

          ex_class = Amazon::AWS::Error.const_get( err_class )
          @exception = ex_class.new( err_msg )
        end
      end
    end
  end
end
</code></pre>

<p>This means that if you get an errorcode like <code>AWS.InvalidParameterValue</code>, this will produce (in its exception variable) a new class <code>Amazon::AWS::Error::InvalidParameterValue</code> which is a subclass of <code>StandardError</code>.</p>

<p>Now here's where it gets weird. I have some code that looks like this:</p>

<pre><code>begin
  do_aws_stuff
rescue Amazon::AWS::Error =&gt; error
  puts "Got an AWS error"
end
</code></pre>

<p>Now, if <code>do_aws_stuff</code> throws a <code>NameError</code>, my rescue block gets triggered. It seems that Amazon::AWS::Error isn't the superclass of the generated error - I guess since it's a module everything is a subclass of it? Certainly if I do:</p>

<pre><code>irb(main):007:0&gt; NameError.new.kind_of?(Amazon::AWS::Error)
=&gt; true
</code></pre>

<p>It says <code>true</code>, which I find confusing, especially given this:</p>

<pre><code>irb(main):009:0&gt; NameError.new.kind_of?(Amazon::AWS)
=&gt; false
</code></pre>

<p>What's going on, and how am I supposed to separate out AWS errors from other type of errors? Should I do something like:</p>

<pre><code>begin
  do_aws_stuff
rescue =&gt; error
  if error.class.to_s =~ /^Amazon::AWS::Error/
    puts "Got an AWS error"
  else
    raise error
  end
end
</code></pre>

<p>That seems exceptionally janky. The errors thrown aren't class AWSError either - they're raised like this:</p>

<pre><code>error = Amazon::AWS::Error::AWSError.new( xml )
raise error.exception
</code></pre>

<p>So the exceptions I'm looking to <code>rescue</code> from are the generated exception types that only inherit from StandardError.</p>

<p>To clarify, I have two questions:</p>

<ol>
<li><p>Why is NameError, a Ruby built in exception, a <code>kind_of?(Amazon::AWS::Error)</code>, which is a module?<br>
<strong>Answer:</strong> I had said <code>include Amazon::AWS::Error</code> at the top of my file, thinking it was kind of like a Java import or C++ include. What this actually did was add everything defined in <code>Amazon::AWS::Error</code> (present and future) to the implicit Kernel class, which is an ancestor of every class. This means <strong>anything</strong> would pass <code>kind_of?(Amazon::AWS::Error)</code>.</p></li>
<li><p>How can I best distinguish the dynamically-created exceptions in <code>Amazon::AWS::Error</code> from random other exceptions from elsewhere?</p></li>
</ol>

[{'answer_id': 70127, 'author': 'Mike Stone', 'author_id': 122, 'author_profile': 'https://Stackoverflow.com/users/122', 'pm_score': 1, 'selected': False, 'text': '<p>Well, from what I can tell:</p>\n\n<pre><code>Class.new( StandardError )\n</code></pre>\n\n<p>Is creating a new class with StandardError as the base class, so it is not going to be a Amazon::AWS::Error at all.  It is just defined in that module, which is probably why it is a kind_of? Amazon::AWS::Error.  It probably isn\'t a kind_of? Amazon::AWS because maybe modules don\'t nest for purposes of kind_of? ?</p>\n\n<p>Sorry, I don\'t know modules very well in Ruby, but most definitely the base class is going to be StandardError.</p>\n\n<p><strong>UPDATE</strong>: By the way, <a href="http://www.ruby-doc.org/core/classes/Object.html#M000370" rel="nofollow noreferrer">from the ruby docs</a>:</p>\n\n<blockquote>\n  <p>obj.kind_of?(class) => true or false</p>\n  \n  <p>Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.</p>\n</blockquote>\n'}, {'answer_id': 70231, 'author': 'Jean', 'author_id': 7898, 'author_profile': 'https://Stackoverflow.com/users/7898', 'pm_score': 4, 'selected': True, 'text': '<p>Ok, I\'ll try to help here : </p>\n\n<p>First a module is not a class, it allows you to mix behaviour in a class. second see the following example : </p>\n\n<pre><code>module A\n  module B\n    module Error\n      def foobar\n        puts "foo"\n      end\n    end\n  end\nend\n\nclass StandardError\n  include A::B::Error\nend\n\nStandardError.new.kind_of?(A::B::Error)\nStandardError.new.kind_of?(A::B)\nStandardError.included_modules #=&gt; [A::B::Error,Kernel]\n</code></pre>\n\n<p>kind_of? tells you that yes, Error does possess All of A::B::Error behaviour (which is normal since it includes A::B::Error) however it does not include all the behaviour from A::B and therefore is not of the A::B kind. (duck typing)</p>\n\n<p>Now there is a very good chance that ruby-aws reopens one of the superclass of NameError and includes Amazon::AWS:Error in there. (monkey patching)</p>\n\n<p>You can find out programatically where the module is included in the hierarchy with the following :</p>\n\n<pre><code>class Class\n  def has_module?(module_ref)\n    if self.included_modules.include?(module_ref) and not self.superclass.included_modules.include?(module_ref)                      \n        puts self.name+" has module "+ module_ref.name          \n    else\n      self.superclass.nil? ? false : self.superclass.has_module?(module_ref)\n    end        \n  end\nend\nStandardError.has_module?(A::B::Error)\nNameError.has_module?(A::B::Error)\n</code></pre>\n\n<p>Regarding your second question I can\'t see anything better than </p>\n\n<pre><code>begin \n#do AWS error prone stuff\nrescue Exception =&gt; e\n  if Amazon::AWS::Error.constants.include?(e.class.name)\n    #awsError\n  else\n    whatever\n  end \nend\n</code></pre>\n\n<p>(edit -- above code doesn\'t work as is : name includes module prefix which is not the case of the constants arrays. You should definitely contact the lib maintainer the AWSError class looks more like a factory class to me :/ )</p>\n\n<p>I don\'t have ruby-aws here and the caliban site is blocked by the company\'s firewall so I can\'t test much further. </p>\n\n<p>Regarding the include : that might be the thing doing the monkey patching on the StandardError hierarchy. I am not sure anymore but most likely doing it at the root of a file outside every context is including the module on Object or on the Object metaclass. (this is what would happen in IRB, where the default context is Object, not sure about in a file)</p>\n\n<p>from the <a href="http://www.rubycentral.com/pickaxe/tut_modules.html" rel="nofollow noreferrer">pickaxe on modules</a> :</p>\n\n<p><code>A couple of points about the include statement before we go on. First, it has nothing to do with files. C programmers use a preprocessor directive called #include to insert the contents of one file into another during compilation. The Ruby include statement simply makes a reference to a named module. If that module is in a separate file, you must use require to drag that file in before using include.</code></p>\n\n<p>(edit -- I can\'t seem to be able to comment using this browser :/ yay for locked in platforms) </p>\n'}, {'answer_id': 71517, 'author': '0124816', 'author_id': 11521, 'author_profile': 'https://Stackoverflow.com/users/11521', 'pm_score': 1, 'selected': False, 'text': '<p>Just wanted to chime in: I would agree this is a bug in the lib code. It should probably read:</p>\n\n<pre><code>      unless Amazon::AWS::Error.const_defined?( err_class )\n        kls = Class.new( StandardError )\n        Amazon::AWS::Error.const_set(err_class, kls)\n        kls.include Amazon::AWS::Error\n      end\n</code></pre>\n'}, {'answer_id': 1517791, 'author': 'Peter Wagenet', 'author_id': 181916, 'author_profile': 'https://Stackoverflow.com/users/181916', 'pm_score': 0, 'selected': False, 'text': '<p>One issue you\'re running into is that <code>Amazon::AWS::Error::AWSError</code> is not actually an exception. When <code>raise</code> is called, it looks to see if the  first parameter responds to the <code>exception</code> method and will use the result of that instead. Anything that is a subclass of <code>Exception</code> will return itself when <code>exception</code> is called so you can do things like <code>raise Exception.new("Something is wrong")</code>.</p>\n\n<p>In this case, <code>AWSError</code> has <code>exception</code> set up as an attribute reader which it defines the value to on initialization to something like <code>Amazon::AWS::Error::SOME_ERROR</code>. This means that when you call <code>raise Amazon::AWS::Error::AWSError.new(SOME_XML)</code> Ruby ends up calling <code>Amazon::AWS::Error::AWSError.new(SOME_XML).exception</code> which will returns an instance of <code>Amazon::AWS::Error::SOME_ERROR</code>. As was pointed out by one of the other responders, this class is a direct subclass of <code>StandardError</code> instead of being a subclass of a common Amazon error. Until this is rectified, Jean\'s solution is probably your best bet.</p>\n\n<p>I hope that helped explain more of what\'s actually going on behind the scenes.</p>\n'}]
['https://Stackoverflow.com/questions/70074', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11284/']