From fd41d47025830d97b4ef020f677063c9384f8cdf Mon Sep 17 00:00:00 2001 From: Pedro Belo Date: Wed, 26 Nov 2008 17:42:16 -0800 Subject: [PATCH] add the http response to Unauthorized and ResourceNotFound too, in case the user wants to parse the body --- lib/request_errors.rb | 29 ++++++++++++++++------------- lib/rest_client.rb | 4 ++-- spec/request_errors_spec.rb | 10 ++++++++++ 3 files changed, 28 insertions(+), 15 deletions(-) diff --git a/lib/request_errors.rb b/lib/request_errors.rb index cf84d5a..fc5a9e0 100644 --- a/lib/request_errors.rb +++ b/lib/request_errors.rb @@ -7,6 +7,19 @@ module RestClient end end + # Base RestClient exception when there's a response available + class ExceptionWithResponse < Exception + attr_accessor :response + + def initialize(response=nil) + @response = response + end + + def http_code + @response.code.to_i if @response + end + end + # A redirect was encountered; caught by execute to retry with the new url. class Redirect < Exception ErrorMessage = "Redirect" @@ -18,12 +31,12 @@ module RestClient end # Authorization is required to access the resource specified. - class Unauthorized < Exception + class Unauthorized < ExceptionWithResponse ErrorMessage = 'Unauthorized' end # No resource was found at the given URL. - class ResourceNotFound < Exception + class ResourceNotFound < ExceptionWithResponse ErrorMessage = 'Resource not found' end @@ -46,17 +59,7 @@ module RestClient # You can get the status code by e.http_code, or see anything about the # response via e.response. For example, the entire result body (which is # probably an HTML error page) is e.response.body. - class RequestFailed < Exception - attr_accessor :response - - def initialize(response=nil) - @response = response - end - - def http_code - @response.code.to_i if @response - end - + class RequestFailed < ExceptionWithResponse def message "HTTP status code #{http_code}" end diff --git a/lib/rest_client.rb b/lib/rest_client.rb index 99daeca..1bf1d10 100644 --- a/lib/rest_client.rb +++ b/lib/rest_client.rb @@ -201,9 +201,9 @@ module RestClient raise Redirect, url elsif res.code == "401" - raise Unauthorized + raise Unauthorized, res elsif res.code == "404" - raise ResourceNotFound + raise ResourceNotFound, res else raise RequestFailed, res end diff --git a/spec/request_errors_spec.rb b/spec/request_errors_spec.rb index 7cc640e..fe6449b 100644 --- a/spec/request_errors_spec.rb +++ b/spec/request_errors_spec.rb @@ -29,6 +29,16 @@ describe RestClient::RequestFailed do end end +describe RestClient::ResourceNotFound do + it "also has the http response attached" do + begin + raise RestClient::ResourceNotFound, :response + rescue RestClient::ResourceNotFound => e + e.response.should == :response + end + end +end + describe "backwards compatibility" do it "alias RestClient::Request::Redirect to RestClient::Redirect" do RestClient::Request::Redirect.should == RestClient::Redirect