我正处于开发(JSON) API阶段,并决定从ActionController::Metal继承我的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 打电话给我简单的动作
def show
@post = Post.find(params[:id])
end执行永远不会到达rescue_from。它是扔的:
ActiveRecord::RecordNotFound (Couldn't find Post with id=1进入我的日志文件。
我试过了,在生产模式下。服务器使用404进行响应,但是响应体是标准的HTML错误页面,用于JSON请求。
当我将继承从ActionController::Metal更改为ActionController::Base时,效果很好。
您可能会注意到缺少respond_with调用。这是因为我使用拉布尔作为我的模板系统。
因此,问题是:是否有机会让rescue_from与Metal一起工作,或摆脱Metal的响应?
发布于 2013-05-01 19:16:18
以下几点对我有用:
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
endhttps://stackoverflow.com/questions/15976146
复制相似问题