尝试设置 rails API,通过控制台和实际 API 请求都收到此错误:
Rack app error handling request { POST /login } #<NameError: uninitialized constant ActionText::Engine::ApplicationController
这是我的应用程序控制器:
class ApplicationController < ActionController::API
before_action :authorized
def encode_token(payload)
JWT.encode(payload, 's3cr3t')
end
def auth_header
#requesting the header type of authorization (with token) that we will declare through our api requests
# { Authorization: 'Bearer <token>' }
request.headers['Authorization']
end
def decoded_token
if auth_header
#going to take the token and decode it
# we're only concerned about the first index which will be a token with key of *user_id*
token = auth_header.split(' ')[1]
# header: { 'Authorization': 'Bearer <token>' }
begin
JWT.decode('s3cr3t', true, algorithm: 'HS256')
rescue JWT::DecodeError
nil
end
end
end
def logged_in_user
#consults decode_token to check the header for valid information
if decoded_token
user_id = decoded_token[0]['user_id']
@user = User.find_by(id: user_id)
end
end
def logged_in?
#returns true or false
!!logged_in_user
end
def authorized
#consults logged_in? see see if user is authorized
render json: { message: 'Please log in' }, status: :unauthorized unless logged_in?
end
end
当然,我想专门对此错误进行排序(语法错误?),但不确定如何解决 Rails API 中的一般错误(超出状态代码)。有没有我应该遵循的好习惯?
谢谢!
对于NameError: uninitialized constant ActionText::Engine::ApplicationController
,你的ApplicationController
定义在哪里?这似乎是ActionText
要求它在app/controllers/application_controller.rb
与可能来自继承ActionController::Base
。
当您开发 API 时,我不希望您需要 ActionText 并且只是不小心加载了它。你应该看看你的config/application.rb
文件,看看加载了什么。如果有,require 'rails/all'
你应该只加载你真正需要的东西,例如
require "action_controller/railtie"
require "active_record/railtie"
但不确定如何解决 Rails API 中的一般错误(超出状态代码)
就一般错误而言,您可以例如使用rescue_from
这样的
class ApplicationController < ActionController::Base
rescue_from User::NotAuthorized, with: :deny_access # self defined exception
rescue_from ActiveRecord::RecordInvalid, with: :show_errors
rescue_from 'MyAppError::Base' do |exception|
render xml: exception, status: 500
end
private
def deny_access
...
end
def show_errors(exception)
exception.record.new_record? ? ...
end
end
https://apidock.com/rails/ActiveSupport/Rescuable/ClassMethods/rescue_from
对于一般错误,实际上并不需要有 a,rescue_from StandardError
因为这是 Rails 的默认行为。Rails 有一个名为的中间件PublicExceptions
,它(主要)执行您想要的操作,因此您可以让 StandardError 传播。
而不是{ error: "Internal Server Error" }
它会呈现这个
{
status: status,
error: Rack::Utils::HTTP_STATUS_CODES.fetch(status, Rack::Utils::HTTP_STATUS_CODES[500])
}
如果出现异常,将呈现{ status: 500, error: "Internal Server Error" }
. 这应该是一个合理的妥协。
对于开发,您可以考虑调整此中间件。您可以使用config.exceptions_app
.
https://guides.rubyonrails.org/configuring.html#rails-general-configuration
https://api.rubyonrails.org/classes/ActionDispatch/PublicExceptions.html
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句