需要抢救使用RESTClient实现401状态码

问题描述 投票:1回答:3

我使用的是Rails的宝石将请求发送到使用RESTClient实现的API。我需要抢救一个401错误代码。我看到RESTClient实现文档如下:

> RestClient.get('http://my-rest-service.com/resource'){ |response,
> request, result, &block|   case response.code   when 200
>     p "It worked !"
>     response   when 423
>     raise SomeCustomExceptionIfYouWant   else
>     response.return!(request, result, &block)   end }

我试图执行一个类似的case语句:

case response.code
 when 200
  JSON.parse(response.body)
 when 401
  raise AuthenicationError, "Unauthorized"
 else
  raise RestClient::ExceptionWithResponse
end

它抓住了200情况不错,但忽视了401的情况下,去直接到人。对上要回来通过RESTClient实现的响应提高对401异常有什么建议?

ruby-on-rails ruby rest-client
3个回答
4
投票

我不能告诉你为什么我敢肯定,其余的客户端回购可以告诉你:) ...但使用则RestClient::Request.new执行API调用与块对我的作品。我认为它可能是与事实的RESTClient实现已建成例外的事情。

request = RestClient::Request.new(
    method: :get,
    url: 'https://my-rest-service.com/resource.json')
response = request.execute {|response| response}
case response.code
  when 200
    puts "Good"
  when 401 
    puts "Bad"
    raise Exception
end

2
投票

它抓住了200情况不错,但忽视了401的情况下,去直接到人。

我有些怀疑它不会去的else,其实;你仍然可以得到,如果你完全拿出else子句甚至提出一个RestClient::ExceptionWithResponse,因为that's what RestClient.get does when it gets an error response such as in the 400 or 500 range。自述:

  • 200和207之间的结果代码,一个RESTClient实现::响应将被退回
  • 为结果代码301,302或307,如果请求是GET或HEAD一个重定向之后,将
  • 为结果代码303,重定向之后,将与所述请求转化成一个GET
  • 对于其他情况下,RESTClient实现:: ExceptionWithResponse持有的回应将提高;一个特定的异常类将抛出已知的错误代码
  • 调用.response异常上获得服务器的响应

0
投票

您正在使用HTTP错误代码。未经授权实际上是401,而不是410。

© www.soinside.com 2019 - 2024. All rights reserved.