Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 24 additions & 8 deletions lib/requests.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class Error < StandardError
attr_reader :response

def initialize(response)
super(response.message)
super(response)

@response = response
end
Expand Down Expand Up @@ -37,11 +37,7 @@ def self.request(method, url,
http.send_request(method, uri, body, headers)
end

if response.is_a?(Net::HTTPSuccess)
Response.new(response.code, response.to_hash, response.body)
else
raise Error, response
end
Response.new(response.code, response.message, response.to_hash, response.body)
end

private
Expand Down Expand Up @@ -76,11 +72,12 @@ def self.process_params(headers: nil, data: nil)

class Response
attr :status
attr :message
attr :headers
attr :body

def initialize(status, headers, body)
@status, @headers, @body = Integer(status), headers, body
def initialize(status, message, headers, body)
@status, @message, @headers, @body = Integer(status), message, headers, body
end

# TODO Verify that JSON can parse data without encoding stuff
Expand All @@ -97,5 +94,24 @@ def encoding
def text
@body
end

def raise_for_status(status=nil)
if status == nil || @status == status
if @status < 300 && status != nil
err_msg = "%d %s" % [@status,@message]
elsif 300 <= @status && @status < 400
err_msg = "Redirection: %d %s" % [@status,@message]
elsif 400 <= @status && @status < 500
err_msg = "Client Error: %d %s" % [@status,@message]
elsif 500 <= @status && @status < 600
err_msg = "Server Error: %d %s" % [@status,@message]
end
end

if err_msg != nil
raise Error, err_msg
end
end

end
end
5 changes: 3 additions & 2 deletions tests/requests_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,10 @@

test 'Error' do
begin
Requests.post('http://httpbin.org/something')
r = Requests.post('http://httpbin.org/something')
r.raise_for_status
rescue Requests::Error => e
assert_equal Net::HTTPNotFound, e.response.class
assert_equal 'Client Error: 404 NOT FOUND', e.response
end
end

Expand Down