Search code examples
rubyrescue

Begin, Rescue with API endpoint


Here is my method:

def get_video_duration
  @time ||= Panda.get("/videos/#{@video.panda_id}/metadata.json")["duration"]
  format_duration
end

I need to write this method "better" in wrapping it with a begin, rescue block so that @time could be nil depending on the response from the API.


Solution

  • Yes, possible using inline rescue clause.

    def get_video_duration
        @time ||= Panda.get("/videos/#{@video.panda_id}/metadata.json")["duration"] rescue nil
        format_duration
    end
    

    Or better explicitly do it.

    def get_video_duration
      @time ||= Panda.get("/videos/#{@video.panda_id}/metadata.json")["duration"]
    rescue YourException
      @time = nil
      format_duration
    end