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

时间:2019-07-06 08:13:06

标签: ruby-on-rails ruby exception syntax

我在Handler目录中创建了一个名为app/exceptions的异常处理类。类文件的完整路径为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配置中,我试图将其分配为例外应用。

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,结果相似。

任何人都可以提供正确的代码来加载异常处理程序吗?

1 个答案:

答案 0 :(得分:0)

您的Handler类未嵌套在module Exception中,因此Exception::Handler不存在。

使用

config.exceptions_app = Handler.new

相反应该起作用。

相关问题