项目作者: gsamokovarov

项目描述 :
Catch all of them Net::HTTP timeout errors.
高级语言: Ruby
项目地址: git://github.com/gsamokovarov/timeout_errors.git
创建时间: 2015-02-27T22:34:57Z
项目社区:https://github.com/gsamokovarov/timeout_errors

开源协议:MIT License

下载


Timeout Errors

Catch all of them Net::HTTP timeout errors. Why? Because there are lots of
them.

Install

Add this line to your application’s Gemfile:

  1. gem 'timeout_errors'

Play

Let’s playing a game. You do a request. It times out. You try to guess which
error it timed out with. Here’s how you win every time.

  1. require 'uri'
  2. require 'timeout_errors'
  3. begin
  4. uri = URI.parse("http://imsuresomeonewillregisterthatjusttotroll.me/")
  5. Net::HTTP.get_response(uri)
  6. rescue TimeoutErrors => e
  7. puts "And the winner is: #{e.inspect}"
  8. end

Now, imagine your favourite 3rd party HTTP client library, that uses net/http
under the hook invents yet another one of those pesky timeout errors. If you
play the game with that specific 3rd party library, you are quite likely to
loose. Here’s how you can improve your chances:

  1. require 'best_http_client_ever_because_we_need_yet_another_one'
  2. require 'timeout_errors'
  3. TimeoutErrors.include_error(
  4. BestHttpClientEverBecauseWeNeedYetAnotherOne::YetAnotherTimeoutToSolveItAllError
  5. )
  6. begin
  7. BestHttpClientEverBecauseWeNeedYetAnotherOne.get(
  8. "http://imsuresomeonewillregisterthatjusttotroll.me/"
  9. )
  10. rescue TimeoutErrors => e
  11. puts "Your favourite timeout error is: #{e.inspect}"
  12. end

Quite useful, heh?

Winners

Here’s the list of errors caught by TimeoutErrors by default.

  • EOFError
  • Errno::ECONNREFUSED
  • Errno::ECONNRESET
  • Errno::EHOSTUNREACH
  • Errno::EINVAL
  • Errno::ENETUNREACH
  • Errno::EPIPE
  • Errno::ETIMEDOUT
  • Net::HTTPBadResponse
  • Net::HTTPHeaderSyntaxError
  • Net::ProtocolError
  • SocketError
  • Timeout::Error

Note that you can fill this list during runtime with
TimeoutErrors.include_error.

Why

There is a lot of previous art on this topic. Why create another one?

net_http_timeout_errors

This library is a great choice. It uses standard Ruby interface and clearly
lists all the errors. However, I wanna catch them all with a single rescue ErrorMatcher clause. Which leads us to net_http_exception_fix.

net_http_exception_fix

net_http_exception_fix is a hotfix to give those common exceptions that pop
up from Net:HTTP usage a shared parent exception class. This is the interface I
like, however it is achieved through polluting builtin’ errors ancestor chain.

How

Instead of introducing extra interface, or monkey patching existing errors,
this library exploits a fun little fact about Ruby’s exception handling. Errors
listed on the rescue clause are matched with the case (===) operator.

Credits

Thanks to the authors and contributors of net_http_timeout_errors and
net_http_exception_fix.