How to handle exceptions with Ruby Rest-Client

余生长醉 提交于 2019-12-02 23:22:43

See heading Exceptions on http://rubydoc.info/gems/rest-client/

  • for results code between 200 and 207 a RestClient::Response will be returned
  • for results code 301, 302 or 307 the redirection will be followed if the request is a get or a head
  • for result code 303 the redirection will be followed and the request transformed into a get
  • for other cases a RestClient::Exception holding the Response will be raised, a specific exception class will be thrown for know error codes

RestClient.get 'http://example.com/resource'
➔ RestClient::ResourceNotFound: RestClient::ResourceNotFound`

begin
  RestClient.get 'http://example.com/resource'
rescue => e
  e.response
end
➔ 404 Resource Not Found | text/html 282 bytes
Raphael

Also in the same documentation @wich pointed to, you can pass a block to RestClient.get such that it will not throw an exception on non-200 response codes:

# Don't raise exceptions but return the response
RestClient.get('http://example.com/resource'){|response, request, result| response }

See the "Result Handling" section: http://www.rubydoc.info/gems/rest-client/1.6.7/frames#Result_handling

rescue RestClient::ExceptionWithResponse => err

There are several errors that could happen, specific exception types like Errno::EHOSTUNREACH or the more generic ExceptionWithResponse. Check the readme for more info.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!