首页 > 解决方案 > Rails 未从此操作返回

问题描述

我遇到的问题很简单。基本上,我的视频页面有一个 Rails 操作。它发出一个 HTTP 请求并得到一些响应。但我现在正在尝试添加错误检查。if我的问题是进入区块后它不会离开这个动作。它似乎继续尝试在if块之后运行所有代码......这很糟糕,因为如果它进入if块,这意味着我们没有得到 200 OK 响应。没有什么可跑的。只需抛出一条错误消息即可!

它正在进入if街区(此处为 Gyazo 链接)。

  def videos
    # get current_user's wistia_project_id & authorization token
    @current_user = current_user
    project_id = @current_user.wistia_project_id
    auth_token = "blah"
    request = "https://api.wistia.com/v1/projects/#{project_id}.json?api_password=#{auth_token}"

    @response = HTTP.get(request)

    puts "BEFORE"

    # handle errors (4xx & 5xx)
    # catches client errors and server errors
    # should print out and then LEAVE this entire action. (return)
    if @response.status.client_error? || @response.status.server_error?
      puts "INSIDE"
      render text: "Sorry, error"
      return
    end

    @response = HTTP.get(request).body
    # get embed code for each video using the hashed_id, put in list
    # BUT!!! for some reason it gets here and there's an error 
    # because there is nothing in the response (errors) 
    @video_iframe_urls = JSON.parse(@response)['medias'].map do |p|
      "https://fast.wistia.com/embed/iframe/#{p["hashed_id"]}?version=v1&controlsVisibleOnLoad=true&playerColor=aae3d8"
    end
  end

标签: ruby-on-rails

解决方案


render text: "Sorry, error"

将此行更改为普通

render plain: "Sorry, error"

问题不是

进入 if 块后它不会离开这个动作。

因为渲染不支持文本选项。你的代码实际上是

    if @response.status.client_error? || @response.status.server_error?
      puts "INSIDE"
      render
      return
    end

render 方法默认按动作名称渲染模板名称


推荐阅读