我有以下路线:
Rails.application.routes.draw do
get '/:id', to: 'foo#bar', constraints: { id: /\d+/ }
end
/1用 id #1 加载我的记录。问题是我的路由与 Rails 默认静态页面(404、500 等)冲突。
如何在动态路由正常工作的情况下获得静态错误页面?
例如,如果可能的话,我不介意将我的静态页面移动到/errors/404之类的路线。
编辑 1:
重新打开 ActionDispatch::ShowExceptions 类并更改私有方法 render_exception 是一个非常hacky的解决方案:
配置/应用程序.rb:
require_relative 'boot'
require 'rails/all'
Bundler.require(*Rails.groups)
module MyApp
class Application < Rails::Application
config.load_defaults 5.2
config.exceptions_app = self.routes
end
end
module ActionDispatch
class ShowExceptions
private
def render_exception(request, exception)
backtrace_cleaner = request.get_header "action_dispatch.backtrace_cleaner"
wrapper = ExceptionWrapper.new(backtrace_cleaner, exception)
status = wrapper.status_code
request.set_header "action_dispatch.exception", wrapper.exception
request.set_header "action_dispatch.original_path", request.path_info
request.path_info = "/errors/#{status}"
response = @exceptions_app.call(request.env)
response[1]["X-Cascade"] == "pass" ? pass_response(status) : response
rescue Exception => failsafe_error
$stderr.puts "Error during failsafe response: #{failsafe_error}\n #{failsafe_error.backtrace * "\n "}"
FAILSAFE_RESPONSE
end
end
end
我已更改request.path_info = "/#{status}"
为request.path_info = "/errors/#{status}"
.
我根本不喜欢这个解决方案。