diff --git a/lib/sendgrid_toolkit/abstract_sendgrid_client.rb b/lib/sendgrid_toolkit/abstract_sendgrid_client.rb index 5bd6ed7..d0625d9 100644 --- a/lib/sendgrid_toolkit/abstract_sendgrid_client.rb +++ b/lib/sendgrid_toolkit/abstract_sendgrid_client.rb @@ -16,12 +16,12 @@ def api_post(module_name, action_name, opts = {}) response = HTTParty.post("https://#{SendgridToolkit.base_uri}/#{base_path}.json", :body => get_credentials.merge(opts), :format => :json) - if response.code > 401 + if response.code > 403 raise(SendgridToolkit::SendgridServerError, "The SendGrid server returned an error. #{response.inspect}") - elsif has_error?(response) and - response['error'].respond_to?(:has_key?) and - response['error'].has_key?('code') and - response['error']['code'].to_i == 401 + elsif has_error?(response) && + response['error'].respond_to?(:has_key?) && + response['error'].has_key?('code') && + [401, 403].include?(response['error']['code'].to_i) raise SendgridToolkit::AuthenticationFailed elsif has_error?(response) raise(SendgridToolkit::APIError, response['error']) diff --git a/spec/lib/sendgrid_toolkit/abstract_sendgrid_client_spec.rb b/spec/lib/sendgrid_toolkit/abstract_sendgrid_client_spec.rb index 6188eaf..2d201d1 100644 --- a/spec/lib/sendgrid_toolkit/abstract_sendgrid_client_spec.rb +++ b/spec/lib/sendgrid_toolkit/abstract_sendgrid_client_spec.rb @@ -16,6 +16,13 @@ @obj.send(:api_post, "profile", "get", {}) }.should raise_error SendgridToolkit::AuthenticationFailed end + it "throws error when bad username or password presented" do + FakeWeb.register_uri(:post, %r|https://#{REGEX_ESCAPED_BASE_URI}/stats\.getAdvanced\.json\?|, :body => '{"error":{"code":403,"message":"Bad username / password"}}', :status => ['403', 'Forbidden']) + @obj = SendgridToolkit::AbstractSendgridClient.new("fakeuser", "fakepass") + expect { + @obj.send(:api_post, "stats", "getAdvanced", {}) + }.to raise_error SendgridToolkit::AuthenticationFailed + end it "thows error when sendgrid response is a server error" do FakeWeb.register_uri(:post, %r|https://#{REGEX_ESCAPED_BASE_URI}/profile\.get\.json|, :body => '{}', :status => ['500', 'Internal Server Error']) @obj = SendgridToolkit::AbstractSendgridClient.new("someuser", "somepass")