Bruce1138 Bruce1138 - 28 days ago 26
Ruby Question

Need to rescue 401 status code using RestClient

I am using a Rails gem to send requests to an api using RestClient. I need to rescue a 401 error code. I saw the following on RestClient documentation:

> 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 }


I have attempted to implement a similar case statement:

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


It captures the 200 case fine but ignores the 401 case and goes straight to the else. Any suggestions on raising an exception for 401 on a response that's coming back through RestClient?

Answer

I can't tell you and why I'm sure the rest-client repo can tell you :) ... but using RestClient::Request.new then executing the api call with a block works for me. I think it probably has to do with the fact that the RestClient has built in exceptions.

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