【发布时间】: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