gpt4 book ai didi

ruby-on-rails-4 - 如何在Rails 4中返回404 JSON格式?

转载 作者:行者123 更新时间:2023-12-04 13:16:30 26 4
gpt4 key购买 nike

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

我发现了很多帖子,但没有运气,仅适用于Rails 3。

在我的 Controller 中,我可以捕获到异常

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

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

最佳答案

使用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

关于ruby-on-rails-4 - 如何在Rails 4中返回404 JSON格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23332320/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com