如何处理 Rails API 中的一般错误?

詹姆斯·斯特拉特

尝试设置 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

https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/middleware/public_exceptions.rb#L14

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何处理Dropbox Java API中的错误

如何处理API21中的shouldInterceptRequest参数更改?

如何处理Rails / Mongoid中的出队连接超时?

如何处理API回应

如何处理Web API Controller-Get Method,MVC 4中的“未找到”错误?

如何处理Rails中的graphql突变中的错误

如何处理异步/等待获取API中的错误404

在Rails中如何处理基于用户的动态颜色变化?

Vuex如何处理API错误通知?

如何处理从API接收的数据类中的信息

如何处理API请求中的不同响应代码?

如何处理Rails ENCRYPTED凭证文件中的合并冲突

使用API时如何处理不同的错误?

如何处理Ruby / Rails中的内存泄漏

如何处理Rails枚举?

使用Rails作为REST API时如何处理多对多记录

一般如何处理API的薪资提高,但更具体而言,如何处理Twitter

在 Rails 本地开发过程中,图像存储通常是如何处理的?

如何处理 Dynamics CRM API 中的选项设置?

无法解决 REST API 中的一般错误

如何解决 Zoho Project API 一般错误 6500?

如何处理来自 Rails 中 gems 的网络请求的渲染 json 错误?

如何处理网关 API 和 Lambda 代理的错误?

API 设计:如何处理第三方的 API 错误

如何处理来自 Node.js 中 API 的 HTTPs json 格式错误?

如何处理 C 中的 typedef 数据类型(一般来说)?

如何处理 NestJS 中的 BodyParser 错误(以及一般的中间件错误)

如何处理来自 API 请求抖动的错误

在 api 驱动的网站中如何处理传统功能?