处理rails应用程序中的rack_throttle异常 [英] Processing rack_throttle exceptions in rails application

查看:122
本文介绍了处理rails应用程序中的rack_throttle异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当速率限制超出时,我如何处理由rack-throttle gem产生的错误?
现在我得到一个包含以下内容的回复:

How can i process errors generated by rack-throttle gem when rate limit is excedeed? Now i just get a response containing the following:

Internal Server Error

undefined method `each' for "403 Forbidden (Rate Limit Exceeded)\n":String

这是堆栈跟踪

ERROR NoMethodError: undefined method `each' for "403 Forbidden (Rate Limit Exceeded)\n":String
/home/rkapitonov/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.1/lib/active_record/query_cache.rb:45:in `each'
/home/rkapitonov/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.1/lib/active_record/connection_adapters/abstract/connection_pool.rb:458:in `each'
/home/rkapitonov/.rvm/gems/ruby-1.9.2-p290/gems/rack-1.3.6/lib/rack/body_proxy.rb:23:in `method_missing'
/home/rkapitonov/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.1/lib/rails/rack/content_length.rb:26:in `call'
/home/rkapitonov/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.1/lib/rails/rack/log_tailer.rb:14:in `call'
/home/rkapitonov/.rvm/gems/ruby-1.9.2-p290/gems/rack-1.3.6/lib/rack/handler/webrick.rb:59:in `service'
/home/rkapitonov/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/webrick/httpserver.rb:111:in `service'
/home/rkapitonov/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/webrick/httpserver.rb:70:in `run'
/home/rkapitonov/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/webrick/server.rb:183:in `block in start_thread'

如何处理此错误并呈现一些自定义文件或进行重定向?

How can i process this error and render some custom file or make a redirect?

推荐答案

最后我找到了一个解决方案

Finally i found a solution

问题出在 rack-throttle gem。响应体应该是一个字符串数组,所以为了解决这个问题,我只是重写了 http_error 方法,这对我来说很有用。
您应该 http_status(代码)+(message.nil??\ n:(#{message})\ n) an数组所以只需将它放在方括号中。

The problem was in rack-throttle gem. Response body should be an array of strings, so to fix the issue i've just overridden http_error method and that did the trick for me. You should make http_status(code) + (message.nil? ? "\n" : " (#{message})\n") an array so just take it in square brackets.

class Rack::Throttle::Limiter
  def http_error(code, message = nil, headers = {})
    [code, {'Content-Type' => 'text/plain; charset=utf-8'}.merge(headers),
    [http_status(code) + (message.nil? ? "\n" : " (#{message})\n")]]
  end
end

把它放在 config / initializers中/rack_throttle.rb 。文件的名称可以更改为您喜欢的任何内容。

Put this inside config/initializers/rack_throttle.rb. The name of the file may be changed to whatever you like.

这篇关于处理rails应用程序中的rack_throttle异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆