Some historical notes are below. As of June 25, 2021, my PR to Rails https://github.com/rails/rails/pull/42592 https://github.com/rails/rails/pull/42592 has been accepted and this functionality will be available in Rails 6.1.5 7.0.0 https://github.com/rails/rails/blob/v7.0.0/actionpack/CHANGELOG.md#rails-700alpha1-september-15-2021
方法一
很容易被删除DebugExceptions
来自应用程序 Rails 堆栈的中间件。
config/application.rb
:
config.middleware.delete ActionDispatch::DebugExceptions
问题在于,正是中间件决定了 Rails 找不到路由并抛出异常ActionController::RoutingError
在这种情况下。因此,如果您想在您的系统中对此异常做出反应exceptions_app
,这种方法对你来说是不行的。
如果您可以看到 HTTP 状态 404 和纯文本响应,请继续使用此方法Not found
当没有找到路线时。
方法2
猴子补丁或更改ActionDispatch::DebugExceptions
某种程度上来说。事实上,早在2013年就有人提议改变DebugExceptions
行为,以便它跳过在中注册的日志记录异常rescue_responses
: 9343 https://github.com/rails/rails/issues/9343,里面有一个示例代码。
我认为覆盖整个类太过分了,所以我选择覆盖它的method log_error https://github.com/rails/rails/blob/5-2-1/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb#L161负责记录错误。
lib/ext/suppress_exceptions.rb
:
module Ext
module SuppressExceptions
private
def log_error(_request, wrapper)
exception = wrapper.exception
return if ActionDispatch::ExceptionWrapper.rescue_responses.key? exception.class.name
super
end
end
end
config/initializers/error_handling.rb
:
require_dependency 'ext/suppress_exceptions'
ActiveSupport.on_load(:action_controller) do
ActionDispatch::DebugExceptions.prepend Ext::SuppressExceptions
end