• 主页
  • Rails -在配置块中加载自定义异常处理程序时出现问题

Rails -在配置块中加载自定义异常处理程序时出现问题

我在app/exceptions目录中创建了一个名为Handler的异常处理类。类文件的完整路径为app/exceptions/handler.rb

class Handler

  def initialize
  end

  def call(env)
    request      = ActionDispatch::Request.new(env)
    status       = request.path_info[1..-1].to_i
    begin
      content_type = request.formats.first
    rescue Mime::Type::InvalidMimeType
      content_type = Mime[:text]
    end
    body = { status: status, error: Rack::Utils::HTTP_STATUS_CODES.fetch(status, Rack::Utils::HTTP_STATUS_CODES[500]) }
    render(status, content_type, body)
  end

  private
    def render(status, content_type, body)
      # format = "to_#{content_type.to_sym}" if content_type
      # if format && body.respond_to?(format)
      #   render_format(status, content_type, body.public_send(format))
      # else
      #   render_html(status)
      # end
      render(111, 'application/json', '{message: "Haan Bhai! Hogaya!"}')
    end

    def render_format(status, content_type, body)
      [status, { "Content-Type" => "#{content_type}; charset=#{ActionDispatch::Response.default_charset}",
                  "Content-Length" => body.bytesize.to_s }, [body]]
    end

    def render_html(status)
      path = "#{public_path}/#{status}.#{I18n.locale}.html"
      path = "#{public_path}/#{status}.html" unless (found = File.exist?(path))

      if found || File.exist?(path)
        render_format(status, "text/html", File.read(path))
      else
        [404, { "X-Cascade" => "pass" }, []]
      end
    end
end

config/application.rb的Rails配置中,我尝试将其指定为exceptions应用程序。

module MyApplication
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 5.2

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration can go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded after loading
    # the framework and any gems in your application.

    # Only loads a smaller set of middleware suitable for API only apps.
    # Middleware like session, flash, cookies can be added back manually.
    # Skip views, helpers and assets when generating a new resource.
    config.api_only = true

    config.exceptions_app = ::Exceptions::Handler.new
  end
end

这会导致错误。

uninitialized constant Exceptions (NameError)

我也尝试过config.exceptions_app = Exceptions::Handler.new,也有类似的结果。

是否有人可以帮助编写正确的代码来加载异常处理程序?

转载请注明出处:http://www.jubohx.com/article/20230428/2409821.html