【问题标题】:Rails with custom error through routes - read original requested URL通过路由自定义错误的 Rails - 读取原始请求的 URL
【发布时间】:2017-10-01 23:14:45
【问题描述】:

我正在使用自定义错误控制器。我希望在访问 500 页面 URL 时获得 200 响应代码(否则我拦截 500 响应代码的中间件会在我想炫耀我的 500 时向我发送异常电子邮件)

似乎使用 self.routes 作为 exceptions_app 会将 request.path 更改为始终等于错误号

目标

  • 访问 www.example.com/crashy_url # => 应该显示带有 500 响应代码的自定义 500 错误模板
  • 访问 www.example.com/500 # => 应该显示带有 200 响应代码的自定义 500 错误模板

问题

  • 访问 www.example.com/crashy_url # => request.path 等于 `/500' 所以我的控制器发送一个 200 响应代码

如何用这个提取真正访问过的 URL?

# config/application.rb
config.exceptions_app = self.routes

# routes
match '/500', to: 'errors#server_error', via: :all

# app/controllers/errors_controller.rb
def server_error
    @status = 500
    can_be_visited_with_ok_response_code
    show
  end

def can_be_visited_with_ok_response_code
    # We want to hide hide the faulty status if the user only wanted to see how our beautiful /xxx page looks like
    # BUT `action_dispatch/middleware/debug_exceptions` will change request.path to be equal to the error !!
    # @status = 200 if request.path == "/#{@status}" # BAD request.path will always return response code
  end

  def show
    respond_to do |format|
      format.html { render 'show', status: @status }
      format.all  { head @status }
    end
  end

【问题讨论】:

    标签: ruby-on-rails error-handling ruby-on-rails-5 actiondispatch


    【解决方案1】:

    我喜欢 Ruby 和 did_you_mean...我能够猜到正确的方法名称:应该使用 request.original_fullpath 来获取用户输入的原始 URL。

    @status = 200 if request.original_fullpath == "/#{@status}"
    

    请注意,request.original_url 还可以为您提供包括主机名在内的完整路径

    【讨论】:

      猜你喜欢
      • 2012-04-15
      • 2014-09-30
      • 2015-12-12
      • 1970-01-01
      • 2017-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多