【问题标题】:How to add attributes to json exception response in rails 5如何在rails 5中为json异常响应添加属性
【发布时间】:2017-04-27 21:42:00
【问题描述】:

当我在我的 api REST 应用程序中调用服务时,例如“localhost/api/boxes/56”,其 id 值在我的数据库中不存在,我收到 RecordNotFoundException 并且呈现的 json 如下所示:

{
  "status": 404,
  "error": "Not Found",
  "exception": "#<ActiveRecord::RecordNotFound: Couldn't find Box with 'id'=56>",
  "traces": {
    "Application Trace": [
      {
        "id": 1,
        "trace": "app/controllers/api/v1/boxes_controller.rb:47:in `set_box'"
      }
    ],
    "Framework Trace": [
      {
        "id": 0,
        "trace": "activerecord (5.0.2) lib/active_record/core.rb:173:in `find'"
      },...
    ],
    "Full Trace": [
      {
        "id": 0,
        "trace": "activerecord (5.0.2) lib/active_record/core.rb:173:in `find'"
      },...
    ]
  }
}

我要如何以及覆盖什么类以在此异常中添加“消息”属性?

【问题讨论】:

    标签: ruby-on-rails json ruby-on-rails-5


    【解决方案1】:

    如果通过您自己的验证未找到记录,您可以处理,如果您尝试通过 id 或任何其他方式在数据库中获取记录:

    record = Record.find(params[:id])
    

    然后你可以检查该记录是否为nil,因为找不到它,可能是一个错误的请求,然后根据需要渲染json,例如:

    if !record.nil?
      render json: record, status: 200
    else
      render json: bad_request
    end
    

    bad_request 方法是在ApplicationController 中定义的,比如:

    def bad_request
      {
        error: 'Record not found, maybe a bad request',
        status: 400
      }
    end
    

    或者另一方面,如果您想直接在您被触发的方法上处理并设置您自己对该行为的响应,那么您可以rescue ActiveRecord::RecordNotFound 异常,例如:

    def show
      box = Box.find(params[:id])
      render json: box, status: 200
    rescue ActiveRecord::RecordNotFound
      render json: { error: 'Baaaaaad' }
    end
    

    此外,如果您想让此操作可用于您的所有模型,您可以在 ApplicationController 中使用 rescue_from 方法并将异常设置为“catch”,然后设置将响应的方法,例如:

    class ApplicationController < ActionController::Base
      ...
      rescue_from ActiveRecord::RecordNotFound, with: :damn_nothing_found
    
      def damn_nothing_found
        render json: { error: 'nothing found :c' }, status: :not_found
      end
    end
    

    【讨论】:

    • Cada opción está mejor que la anterior, muchas gracias pequeño :*
    • Jajaja de nada!.
    猜你喜欢
    • 1970-01-01
    • 2011-05-01
    • 2021-05-05
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多