diff --git a/lib/geocoder/lookups/base.rb b/lib/geocoder/lookups/base.rb index 9d0ae8320f533e8c692b16d12685e978a4ef2000..115f914db6ed08cdd309815da0189023d70d8a41 100644 --- a/lib/geocoder/lookups/base.rb +++ b/lib/geocoder/lookups/base.rb @@ -214,6 +214,7 @@ module Geocoder else check_api_key_configuration!(query) response = make_api_request(query) + check_response_for_errors!(response) body = response.body if cache and valid_response?(response) cache[key] = body @@ -223,6 +224,13 @@ module Geocoder body end + def check_response_for_errors!(response) + if response.code.to_i == 401 + raise_error(Geocoder::RequestDenied) || + warn("Geocoding API error: 401 Unauthorized") + end + end + ## # Make an HTTP(S) request to a geocoding API and # return the response object. diff --git a/test/test_helper.rb b/test/test_helper.rb index a59a6f1c4d862118925a19419362752c980d56a0..2309827b16d10b49e1aa5f1dffaaf79f4b8fdf0d 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -347,3 +347,11 @@ class GeocoderTestCase < Test::Unit::TestCase Geocoder.configure(:api_key => key) end end + +class MockHttpResponse + attr_reader :code, :body + def initialize(options = {}) + @code = options[:code].to_s + @body = options[:body] + end +end diff --git a/test/unit/lookup_test.rb b/test/unit/lookup_test.rb index 83561537ab8d37626e5fb4d2242439720966b9ce..5ece0de4b2c6936aecbbbdf81dafb10712e6b94f 100644 --- a/test/unit/lookup_test.rb +++ b/test/unit/lookup_test.rb @@ -56,6 +56,15 @@ class LookupTest < GeocoderTestCase end end + def test_raises_exception_on_401_response + Geocoder.configure(always_raise: [Geocoder::RequestDenied]) + assert_raises Geocoder::RequestDenied do + lookup = Geocoder::Lookup.get(:smarty_streets) + response = MockHttpResponse.new(code: 401) + lookup.send(:check_response_for_errors!, response) + end + end + def test_raises_exception_on_invalid_key Geocoder.configure(:always_raise => [Geocoder::InvalidApiKey]) #Geocoder::Lookup.all_services_except_test.each do |l|