如何在Rails中捕获整个应用程序的ArgumentError?

时间:2014-07-13 11:28:18

标签: ruby-on-rails ruby exception

环境

  • RAILS 3.1
  • Ruby 1.9.1

我已尝试过application_controller,但这似乎不起作用。

我可能做错了什么?

  rescue_from ArgumentError do |exception|
     flash.now[:error] = "Arguments for your request are incorrect"
     #ExceptionNotifier::Notifier.background_exception_notification(exception).deliver if Rails.env.production?
     redirect_to root_url, :alert => exception.message
  end

我正在尝试处理的例外

   A ArgumentError occurred in marketplace#index:

  invalid byte sequence in UTF-8
  .bundle/gems/ruby/1.9.1/gems/rack-1.4.5/lib/rack/utils.rb:104:in `normalize_params'

A ArgumentError occurred in connect#index:

  invalid %-encoding (%u2713)
  .bundle/gems/ruby/1.9.1/gems/rack-1.4.5/lib/rack/backports/uri/common_192.rb:46:in `decode_www_form_component'

1 个答案:

答案 0 :(得分:1)

如果有人还在为此寻找答案,我会参考这个答案 https://stackoverflow.com/a/25842118/697816

application_controller.rb

rescue_from ActionController::RoutingError, with: -> { render_404 }

添加

rescue_from ArgumentError, with: -> { render_404 }

将会抓住你所有的ArgumentError