0

for this moment I have a block like

  begin
    yield
  rescue MyError => e
    call_specific_method
    call_method_foo
    render json: { error: e.to_s }
  rescue ActiveRecord::RecordInvalid => e
    call_specific_method
    call_method_foo
    render json: { error: e.to_s }
  rescue => e
    call_specific_method
    call_method_foo
    render json: { error: e.to_s }
  end

so I have lot of duplicate instructions because they are similar for each exception :

call_method_foo
render json: { error: e.to_s }

but I have specific instructions too :

call_specific_method

I need to do something like :

  begin
    yield
  rescue => e
    if e.type == ActiveRecord::RecordInvalid
       call_specific_method
    elsif e.type == MyError
       call_specific_method
    else
      call_specific_method
    end
    call_method_foo
    render json: { error: e.to_s }
  end

So how can I test type of exception in single rescue ?

Matrix
  • 3,458
  • 6
  • 40
  • 76

1 Answers1

1

You can test the exception class like this:

rescue => e
  if e.is_a?(ActiveRecord::RecordInvalid)
    ...
  end
end

In any case, I'd better extract the common code to an external private method:

def foo
  ...
  begin
    yield
  rescue MyError => e
    call_specific_method
    render_error_for(e)
  rescue ActiveRecord::RecordInvalid => e
    call_specific_method
    render_error_for(e)
  rescue => e
    call_specific_method
    render_error_for(e)
  end
end

def render_error_for(e)
  call_method_foo
  render json: { error: e.to_s }
end
dgilperez
  • 10,716
  • 8
  • 68
  • 96