簡體   English   中英

控制器沒有從 ApplicationController 繼承方法

[英]Controller not inheriting methods from ApplicationController

我有一個僅支持 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 繼承rescue_errors?

看起來這行不通,因為rescue_from在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

你可以這樣做:


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

您可以為每個可能的錯誤創建不同的答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM