使用 ActionController::Metal 处理 ActiveRecord::RecordNotFound

编程入门 行业动态 更新时间:2024-10-26 14:30:57
本文介绍了使用 ActionController::Metal 处理 ActiveRecord::RecordNotFound的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在开发 (JSON) API 阶段并决定从 ActionController::Metal 继承我的 ApiController 以利用速度等.

I'm on the developing (JSON) API stage and decide to inherit my ApiController from ActionController::Metal to took advantages of speed etc.

所以我包含了一堆模块来让它工作.

So I've included a bunch of modules to make it work.

最近我决定在未找到记录时以空结果响应.Rails 已经从 Model#find 方法中抛出 ActiveRecord::RecordNotFound 并且我一直在尝试使用 rescue_from 来捕获它并编写这样的东西:

Recently I've decide to respond with empty result when record not found. Rails already throws ActiveRecord::RecordNotFound from Model#find method and I've been trying to use rescue_from to catch it and write something like this:

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.这是抛出:

And execution never reach rescue_from. It's throws:

ActiveRecord::RecordNotFound (Couldn't find Post with id=1

进入我的日志文件.

我一直在尝试并处于生产模式.服务器以 404 响应,但响应正文是 JSON 请求的标准 HTML 错误页面.

I've been trying it and in production mode. Server responds with 404 but response body is standard HTML error page for JSON request.

当我将继承从 ActionController::Metal 更改为 ActionController::Base 时效果很好.

It's works well when I change inheritance from ActionController::Metal to ActionController::Base.

您可能会注意到缺少 respond_with 调用.那是因为我使用 RABL 作为我的模板系统.

You may notice about lack of respond_with call. That's because I'm using RABL as my template system.

所以问题是:有没有机会让 rescue_fromMetal 一起工作或从响应中摆脱 HTML?

So the question is: Is there any chances to make rescue_from work with Metal or get rid HTML from response?

推荐答案

以下对我有用:

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

这篇关于使用 ActionController::Metal 处理 ActiveRecord::RecordNotFound的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-18 10:34:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/935674.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Metal   ActionController   RecordNotFound   ActiveRecord

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!