46

Net::HTTP::Get (たとえば) からの「成功」(つまり、2xx リターン コード) からの応答を適切にチェックするにはどうすればよいでしょうか? ドキュメントは、この単純な質問について悲しいことに沈黙しているようです。

私は持っている:

response=Net::HTTP.new( host, port ).request my_get_request # details not important

グーグルとほぼランダムなタイピングを繰り返した後、最終的にこれが機能すると判断しました。

response.class < Net::HTTPSuccess

それは実際にそれを行う標準的な方法ですか?

4

3 に答える 3

77

For Net::HTTP, yes, checking the class of the response object is the way to do it. Using kind_of? (aliased also as is_a?) is a bit clearer (but functionally equivalent to using <):

response.kind_of? Net::HTTPSuccess

Calling value on response will also raise a Net::HTTPError if the status code was not a successful one (what a poorly named method…).

If you can, you may want to consider using a gem instead of Net::HTTP, as they often offer better APIs and performance. Typhoeus and HTTParty are two good ones, among others.

于 2012-08-19T00:19:55.627 に答える
22

内部で===caseを使用しているため、慣用的にクラス比較を実行するRuby のステートメントを利用できます。

特定のエラーをキャッチするが、それ以外の場合はサーバーのメッセージを返すだけの JSON クライアントの例を次に示します。

  case response
    when Net::HTTPSuccess
      JSON.parse response.body
    when Net::HTTPUnauthorized
      {'error' => "#{response.message}: username and password set and correct?"}
    when Net::HTTPServerError
      {'error' => "#{response.message}: try again later?"}
    else
      {'error' => response.message}
  end

上記のNet::HTTPResponse 親クラス(例: Net::HTTPServerError) も機能します。

于 2014-04-08T23:12:08.940 に答える