1
0
Fork 0
mirror of https://github.com/jnunemaker/httparty synced 2023-03-27 23:23:07 -04:00

Adding option to throw exceptions on some HTTP statuses

This commit is contained in:
Daniel Cunha 2015-12-28 19:14:12 -02:00
parent 880a2d575c
commit fc02683c8f
4 changed files with 61 additions and 0 deletions

View file

@ -72,6 +72,16 @@ module HTTParty
default_options[:log_format] = format
end
# Raises HTTParty::ResponseError if response's code matches this statuses
#
# class Foo
# include HTTParty
# raise_on [404, 500]
# end
def raise_on(codes = [])
default_options[:raise_on] = *codes
end
# Allows setting http proxy information to be used
#
# class Foo

View file

@ -17,6 +17,8 @@ module HTTParty
logger = ::HTTParty::Logger.build(request.options[:logger], request.options[:log_level], request.options[:log_format])
logger.format(request, self)
end
throw_exception
end
def parsed_response
@ -77,6 +79,12 @@ module HTTParty
super
end
end
def throw_exception
if @request.options[:raise_on] && @request.options[:raise_on].include?(code)
::Kernel.raise ::HTTParty::ResponseError.new(@response), "Code #{code} - #{body}"
end
end
end
end

View file

@ -43,6 +43,33 @@ RSpec.describe HTTParty::Response do
it "should set code as a Fixnum" do
expect(@response.code).to be_an_instance_of(Fixnum)
end
context 'when raise_on is supplied' do
let(:request) { HTTParty::Request.new(Net::HTTP::Get, '/', raise_on: [404]) }
context "and response's status code is in range" do
let(:body) { 'Not Found' }
let(:response) { Net::HTTPNotFound.new('1.1', 404, body) }
before do
allow(response).to receive(:body).and_return(body)
end
subject { described_class.new(request, response, @parsed_response) }
it 'throws exception' do
expect{ subject }.to raise_error(HTTParty::ResponseError, "Code 404 - #{body}")
end
end
context "and response's status code is not in range" do
subject { described_class.new(request, @response_object, @parsed_response) }
it 'does not throw exception' do
expect{ subject }.not_to raise_error(HTTParty::ResponseError)
end
end
end
end
it "returns response headers" do

View file

@ -525,6 +525,22 @@ RSpec.describe HTTParty do
end
end
describe ".raise_on" do
context 'when parameters is an array' do
it 'sets raise_on option' do
@klass.raise_on [500, 404]
expect(@klass.default_options[:raise_on]).to contain_exactly(404, 500)
end
end
context 'when parameters is a fixnum' do
it 'sets raise_on option' do
@klass.raise_on 404
expect(@klass.default_options[:raise_on]).to contain_exactly(404)
end
end
end
describe "with explicit override of automatic redirect handling" do
before do
@request = HTTParty::Request.new(Net::HTTP::Get, 'http://api.foo.com/v1', format: :xml, no_follow: true)