【问题标题】:How can I return a 404 JSON format in Rails 4?如何在 Rails 4 中返回 404 JSON 格式?
【发布时间】:2014-06-13 11:34:00
【问题描述】:

我是 Ruby 的新手。我正在使用 Rails 4 编写一个 Restful API 应用程序。 找不到记录时如何返回 404 JSON not found 字符串?

我找到了很多帖子,但没有运气,只针对 Rails 3。

在我的控制器中我可以捕捉到异常

  def show
    country = Country.find(params[:id])
    render :json => country.to_record
  rescue Exception
    render :json => "404"
  end

但我想要一个通用的来捕获所有未找到的资源。

【问题讨论】:

    标签: ruby-on-rails-4


    【解决方案1】:

    做:

    def show
      country = Country.find(params[:id])
      render :json => country.to_record
    rescue Exception
      render :json => 404_json_text, :status => 404
    end
    

    【讨论】:

    【解决方案2】:

    使用rescue_from。见http://guides.rubyonrails.org/v2.3.11/action_controller_overview.html#rescue

    在这种情况下使用类似的东西:

    class ApplicationController < ActionController::Base
      rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
    
      private
      def record_not_found(error)
        render json: { error: error.message }, status: :not_found
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-21
      • 2013-11-21
      • 2013-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 1970-01-01
      相关资源
      最近更新 更多