简体   繁体   English

开始使用API​​端点进行救援

[英]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. 我需要在用beginrescue块包装它时写出“更好”的方法,以便@time可以为零,具体取决于API的响应。

Yes, possible using inline rescue clause. 是的,可以使用内联 rescue子句。

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

Maybe break it down with an additional method : 也许用其他方法将其分解:

def fetch_video_duration

  Panda.get("/videos/#{@video.panda_id}/metadata.json")["duration"]

  rescue
    return nil
end

def get_video_duration
  @time ||= fetch_video_duration

  format_duration
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM