【问题标题】:Controller not inheriting methods from ApplicationController控制器没有从 ApplicationController 继承方法
【发布时间】:2020-04-16 17:23:18
【问题描述】:

我有一个只有 Rails 6 API 的项目,它表现得很奇怪。

我的应用程序控制器有一个方法来挽救常见的异常:

class ApplicationController < ActionController::API
  before_action :rescue_errors

  private

  def rescue_errors
    rescue_from ActiveRecord::RecordNotFound do
      render json: { error: { message: ['Record not found'] } }, status: :not_found
    end
  end
end

这是我的用户控制器:

class Api::V1::User::UsersController < ApplicationController
  def show
    user = User.find(params[:id])
    render json: { user_id: user.id }, status: :ok
  end
end

然后我尝试访问一个不存在的用户 id 以获取从 ApplicationController 继承的获救的 RecordNotFound 异常,我收到此错误:

<NoMethodError: undefined method `rescue_errors' for #<Api::V1::User::UsersController:0x00007f71484b3be0>\nDid you mean?  rescue_handlers>

为什么 UserController 不从 ApplicationController 继承救援错误?

【问题讨论】:

  • 您的 Rails 应用程序是仅 API 还是 API 和标准 MVC 两者?
  • 仅限@lacostenycoder API
  • 你之前read the comments是如何定义rescue_from的吗?

标签: ruby-on-rails ruby oop inheritance


【解决方案1】:

看起来这不起作用,因为 rescue_from is implemented 在 Rails 中的方式。它应该在类定义中使用,而不是包含在私有方法中。

所以你应该这样做:

class ApplicationController < ActionController::API
  before_action :rescue_errors

  rescue_from ActiveRecord::RecordNotFound do
    render json: { error: { message: ['Record not found'] } }, status: :not_found
  end    
end

【讨论】:

  • 我以前试过这个,但错误根本没有得到拯救并作为异常抛出:<:recordnotfound: couldn find user with>
  • 当我将“rescue_from...”直接放在 ApplicationController 类上,而不在方法中定义它时,它可以完美运行。但是当我将它放在关注点或方法中时,它就不再起作用了。
【解决方案2】:

你可以这样做:


class ApplicationController < ActionController::API
  rescue_from ActiveRecord::RecordNotFound, with: :not_found_response

  private

  def not_found_response(exception)
    render json: { code: 404, status: 'Not Found', error: exception.message }, status: :not_found
  end
end

您可以为每个可能的错误创建不同的答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 2016-08-14
    • 2019-12-20
    • 2014-09-24
    相关资源
    最近更新 更多