Bruce1138 Bruce1138 - 1 year ago 162
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(''){ |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
when 401
raise AuthenicationError, "Unauthorized"
raise RestClient::ExceptionWithResponse

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 Source

I can't tell you and why I'm sure the rest-client repo can tell you :) ... but using 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 =
    method: :get,
    url: '')
response = request.execute {|response| $results = response}
case response.code
  when 200
    puts "Good"
  when 401 
    puts "Bad"
    raise Exception
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download