【问题标题】:Changing "render" key from "plain" to "json" causes server error将“render”键从“plain”更改为“json”会导致服务器错误
【发布时间】:2021-08-24 18:33:12
【问题描述】:

考虑下面的代码

class AuthenticatedController < ApplicationController
  rescue_from InvalidCredentials, with: :unauthenticated

  def current_user
    raise InvalidCredentials
  end

  private

  def unauthenticated(_error)
    render plain: { error: 'text' }.to_json, status: :unauthorized
  end
end

class UsersController < AuthenticatedController
  def show
    render json: current_user
  end
end

当我请求 Users#show 时,它会呈现 {"error":"text"} 就好了。

但如果我将unauthenticated 更改为

  def unauthenticated(_error)
    render json: { error: 'text' }, status: :unauthorized
  end

资源响应{"status":500,"error":"Internal Server Error"}

堆栈跟踪:

Started GET "/api/v1/user" for ::1 at 2021-08-25 12:24:30 +0300
Processing by Api::V1::UsersController#show as JSON
  Parameters: {"user"=>{}}
Completed 500 Internal Server Error in 1ms (ActiveRecord: 0.0ms | Allocations: 214)

InvalidCredentials (InvalidCredentials):
app/controllers/users_controller.rb:in `show'
app/controllers/authenticated_controller.rb:in `current_user'
app/controllers/authenticated_controller.rb:in `unauthenticated'

所以在处理程序中调用render json: {} 会导致再次引发相同的错误。但同时render plain: '' 没有。

当我将密钥从 plain 更改为 json 时会发生什么,以及在使用 JSON 时如何使其以 :unauthorized 而不是服务器错误响应?

【问题讨论】:

  • stacktrace 中有什么?
  • @AmitPatel 我已经添加了堆栈跟踪。

标签: ruby-on-rails ruby-on-rails-6 active-model-serializers


【解决方案1】:

我使用active_model_serializers 库来呈现 JSON。 它使用renderscope 选项作为要调用的方法名称,它是current_user by default。所以当我调用render json: ... 时库再次调用current_user 方法导致错误。

我已将unauthenticated 方法更改为

  def unauthenticated(_error)
    render json: { error: 'text' }, status: :unauthorized, scope: nil
  end

它开始按预期工作。

【讨论】:

    【解决方案2】:

    根据您提供的信息,问题很可能是您如何使用rescue_from 触发错误的请求必须是 JSON 请求才能使其工作。例如,如果您尝试从表单登录,通常默认情况下是 HTMl 请求。确认这一点的一种方法是在控制器方法中使用raise request.inspect。如果是这种情况,则没有简单的修复方法,您必须自行修复请求或仅支持两者。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-22
      • 2020-11-10
      相关资源
      最近更新 更多