Reputation: 681
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?
Upvotes: 1
Views: 208
Reputation: 681
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
Upvotes: 0
Reputation: 7326
so what I want to do is check if a raised error is a subclass of a list of specific Exceptions.
You can rescue by type(s):
begin
raise B.new
rescue e : A | C
puts "A or C"
rescue B
puts "B"
rescue
puts "any other kind of exception"
end
which prints
# => A or C
Upvotes: 1