Search code examples
exceptionruby-on-rails-4typeerrorrescue

How regroup all rescues of begin block and switch type of error later?


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 ?


Solution

  • 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