I am relatively new to ruby and I am stuck with this problem which is rather hard to solve.
What I want to achieve is that I could catch custom errors which I throw from the sub class in a parent class. Given an example below, how could I make the parent class to understand the RequestTimeout class? Because, now when I run the code it results to a following output:
test_raise.rb:5:in `rescue in handle_errors': uninitialized constant BaseService::RequestTimeout (NameError) from test_raise.rb:4:in `handle_errors' from test_raise.rb:14:in `first_service_method' from test_raise.rb:31:in `<main>' The code:
class BaseService def handle_errors yield rescue RequestTimeout => e # <-- the problem p e.message end end class FirstService < BaseService class RequestTimeout < StandardError; end def first_service_method handle_errors do raise RequestTimeout, "FirstService RequestTimeout" end end end class SecondService < BaseService class RequestTimeout < StandardError; end def second_service_method handle_errors do raise RequestTimeout, "SecondService RequestTimeout" end end end a = FirstService.new a.first_service_method Ofc. I could solve the problem by changing:
rescue RequestTimeout => e to:
rescue => e But I dont want to do that because I wan't to catch multiple exceptions (more than RequestTimeout) which are defined and raised by me. Any help would be awesome!
class RequestTimeout < StandardError; endinto base class. It will become available in all children. Whether you have different exceptions for different child classes, you are forced to use namespaces, as @marek-lipka said below.