ck3*_*k3g 3 api json ruby-on-rails-3
我正处于开发(JSON)API阶段并决定继承我ApiController的ActionController::Metal以利用速度等.
所以我已经包含了一些模块来使它工作.
最近我决定在找不到记录时回复空的结果.Rails已经ActiveRecord::RecordNotFound从Model#find方法抛出了,我一直试图用rescue_from它来捕获它并写下这样的东西:
module Api::V1
class ApiController < ActionController::Metal
# bunch of included modules
include ActiveSupport::Rescuable
respond_to :json
rescue_from ActiveRecord::RecordNotFound do
binding.pry
respond_to do |format|
format.any { head :not_found }
end
end
end
end
Run Code Online (Sandbox Code Playgroud)
打电话给我简单的动作
def show
@post = Post.find(params[:id])
end
Run Code Online (Sandbox Code Playgroud)
执行永远不会到达rescue_from.这是抛出:
ActiveRecord::RecordNotFound (Couldn't find Post with id=1
Run Code Online (Sandbox Code Playgroud)
进入我的日志文件.
我一直在尝试它并处于生产模式.服务器以404响应,但响应正文是JSON请求的标准HTML错误页面.
它的效果很好,当我从改变继承ActionController::Metal到ActionController::Base.
你可能会注意到没有respond_with通话.那是因为我使用RABL作为我的模板系统.
所以问题是:是否有任何机会rescue_from与Metal响应一起使用或摆脱HTML?
小智 6
以下对我有用:
class ApiController < ActionController::Metal
include ActionController::Rendering
include ActionController::MimeResponds
include ActionController::Rescue
append_view_path Rails.root.join('app', 'views').to_s
rescue_from ActiveRecord::RecordNotFound, with: :four_oh_four
def four_oh_four
render file: Rails.root.join("public", "404.html"), status: 404
end
end
Run Code Online (Sandbox Code Playgroud)