【发布时间】:2020-10-13 10:22:49
【问题描述】:
我的控制器中的这段代码有问题:
class Api::V1::BaseController < ActionController::API
include Pundit
after_action :verify_authorized, except: :index
after_action :verify_policy_scoped, only: :index
rescue_from StandardError, with: :internal_server_error
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
rescue_from ActiveRecord::RecordNotFound, with: :not_found
private
def user_not_authorized(exception)
render json: {
error: "Unauthorized #{exception.policy.class.to_s.underscore.camelize}.#{exception.query}"
}, status: :unauthorized
end
def not_found(exception)
render json: { error: exception.message }, status: :not_found
end
def internal_server_error(exception)
if Rails.env.development?
response = { type: exception.class.to_s, message: exception.message, backtrace: exception.backtrace }
else
response = { error: "Internal Server Error" }
end
render json: response, status: :internal_server_error
end
end
问题
rescue_from StandardError 是我所有烦恼的根源。这个控制器工作得很好,当权威错误是唯一发生的错误时,它可以从权威白名单检查中解救出来。
但是,一旦专家同时发生任何其他错误,我就会收到DoubleRenderError,因为两个救援最终都会被触发。我正在寻找一种快速调整,以避免权威人士在另一个错误已经发生时触发,或者针对此问题的替代解决方案。
是否有任何其他错误类可以用来避免过度依赖StandardError?
我尝试过的事情
-
渲染后添加返回
它不起作用。我认为救援链会干扰
render :x and return的正常行为。
非常感谢!
【问题讨论】:
标签: ruby-on-rails api controller pundit rescue