【发布时间】: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