M
M
Maxim Valerievich2015-05-30 21:09:38
API
Maxim Valerievich, 2015-05-30 21:09:38

RoR. How to properly handle an error coming from the API?

Hello. I have a vk_tracks controller, it has an add method, This method adds an audio recording to the user. Sometimes, with a large number of requests, captcha crashes and this captcha needs to be processed. For vk api I use this gem: https://github.com/7even/vkontakte_api
All requests are made via ajax.
Here is the code:

def add
    @vk_track = VkTrack.find(params[:id])
    if params[:captcha]
      id = @vk.audio.add(audio_id: @vk_track.vk_id, owner_id: @vk_track.owner_id, captcha_sid: params[:captcha_sid], captcha_key: params[:captcha])
      respond_to do |format|
        format.html {}
        format.js   {}
      end
    else
      begin
        @vk.audio.add(audio_id: @vk_track.vk_id, owner_id: @vk_track.owner_id)

        respond_to do |format|
          format.html {}
          format.js   {}
        end
      rescue VkontakteApi::Error => @e
        if @e.error_code == 14
          respond_to do |format|
            # тут мы просто выводим модальное окно а в нем картинку с капчей и форму
            format.js { render :file => "vk_tracks/captcha.js.erb" }
          end
        else
          raise
        end
      end
    end
  end

I'm new to ruby ​​and can't figure out how to do it right. Now, when captcha is triggered, a modal window pops up with captcha and a form. This form submits data to the same controller and method. Is there an easier way? And what is the best way to process captcha.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rinat Shaikhutdinov, 2015-06-02
@S-anches

def add
  vk_track = VkTrack.find(params[:id])
  
  @vk.audio.add(audio_params(vk_track))
rescue VkontakteApi::Error => e
  raise e unless e.error_code == 14

  respond_to do |format|
    # Старайтесь не делать ваши вьюхи зависимыми от инстанс-переменных (@var)
    # По возможности, старайтесь использовать partials и передавать
    # зависимости явным образом
    # file: app/views/controller_name/_captcha.js.erb
    # в нем будет доступна переменная exception
    format.js { render partial: 'captcha', exception: e }
  end
end

def audio_params(vk_track)
  {
    audio_id: vk_track.vk_id,
    owner_id: vk_track.owner_id
  }.merge(captcha_params)
end

def captcha_params
  return {} unless params[:captha]

  {
    captcha_sid: params[:captcha_sid],
    captcha_key: params[:captcha]
  }
end

To be honest, I did not check the functionality of the code, but it seems that there should not be any problems.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question