Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

Handle all types of errors except one in Ruby?

I have a method which might throw ParserException with some meaningful description, and throw general ParserException on any StandardError:

Just as a minimal reproducible example:

begin
  item = parseItem(json)

  if !item.id
    raise ParserException.new("id property is missing")
  end

  item
rescue => ex
  raise ParserException.new("exception occurred when tried to parse JSON", ex: ex)
end

Now, the problem is that if the id property is missing, then the ParserException is being caught, wrapped into another ParserException and then re-thrown with less meaningful message.

I can fix it by doing this:

begin 
  # ...
rescue ParserException
  raise
rescue => ex
  raise ParserException.new("exception occurred when tried to parse JSON", ex: ex)
end

But it may look a little ugly. Is there a more laconic way to achieve this? Something like rescue !ParserException => ex?

For example, in C# I can do (this may be considered ugly too, but I am asking because of curiosity):

try
{
    throw new ParserException("Specific error");
catch (Exception ex) when (!(ex is ParserException))
{
    throw new ParserException("Generic error");
}

Upvotes: 1

Views: 216

Answers (1)

3limin4t0r
3limin4t0r

Reputation: 21130

Your current fix is probably the cleanest way to go, however I you don't want that additional rescue block you can also handle it in your catch-all solution.

begin 
  # ...
rescue => ex
  raise if ex.is_a? ParserException
  raise ParserException.new("exception occurred when tried to parse JSON", ex: ex)
end

Upvotes: 3

Related Questions