Search code examples
crystal-lang

Crystal check if subclass of list of classes


So what I want to do is check if a raised error is a subclass of a list of specific Exceptions at runtime. Users can hand in an Array of Exceptions at runtime.

I thought I'd just use is_a? and it works as expected against a single class.

class A < Exception; end
class B < A; end
class C < Exception; end
class D < Exception; end

begin
  raise B.new
rescue e
  puts e.is_a? A
end

But if I then use an array of Exceptions to check, it doesn't work anymore

monitored = [A, C]
begin
  raise B.new
rescue e
  monitored.each do |exception_class|
    puts e.is_a? exception_class
  end
end

The error I get is Syntax error in eval:24: expecting token 'CONST', not 'exception_class' with line 24 being puts e.is_a? exception_class.

puts typeof(exception_class) in the loop prints Exception:Class as expected.

Any ideas what I am doing wrong here?


Solution

  • Apparently this is not possible for the exact case mentioned in the question with the current compiler implementation: https://github.com/crystal-lang/crystal/issues/2060#issuecomment-309711343