Created
October 12, 2015 07:53
-
-
Save mitsuru793/f07903f1e2ea5ce164ca to your computer and use it in GitHub Desktop.
ループ内でopen(url)を使用した関数の例外を補足する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'open-uri' | |
| # 末尾に記述した数値のステータスコードを返してくれるwebサービス | |
| url_root = 'http://ozuma.sakura.ne.jp/httpstatus/' | |
| def open_url(url) | |
| open(url) | |
| end | |
| status_codes = [503, 202, 504] | |
| # open_url内で例外を補足しない理由は、 | |
| # その関数実行後の処理に影響があるかもしれないので。 | |
| status_codes.each do |code| | |
| url = url_root + code.to_s | |
| begin | |
| open_url(url) | |
| rescue OpenURI::HTTPError => e | |
| response = e.io | |
| # response.status => ["503", "Service Unavailable"] | |
| status_code = response.status[0] | |
| puts "#{status_code}: #{url}" | |
| end | |
| end | |
| puts "scrape done" | |
| # => 503: http://ozuma.sakura.ne.jp/httpstatus/503 | |
| # 504: http://ozuma.sakura.ne.jp/httpstatus/504 | |
| # scrape done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment