HTTP Response Handling

40 views
Skip to first unread message

Aureo Ponce

unread,
Mar 10, 2019, 11:34:40 PM3/10/19
to http.rb: a fast, easy-to-use Ruby HTTP client with a chainable API
Hello everyone,

I know through the documentation how to get the status code and content of an HTTP Response. However, what I want to know if there is a way to separate Successful HTTP Request (2xx) from the Unsuccessful one(4xx or 5xx). Similarly how it is handled in Angular + Typescript:

HTTPrequest.subscribe((response) => {
   // successful code
}, (error) => {
   // Unsuccessful code
});

Sure, I could get the code from the request and check whether it is a 2xx code, but just wanted to make sure if this behavior already exist in order to avoid repetition.


Marc Köhlbrugge

unread,
Apr 12, 2020, 5:06:11 PM4/12/20
to http.rb: a fast, easy-to-use Ruby HTTP client with a chainable API
If you don't care about the specific status of the response, but only care about whether it was successful or not you can do something like this:

response = HTTP.get("https://google.com")

if response.status.success?
 
# 2xx code
else
 
# something went wrong
end


You can see in the source code this simply checks if the status code was a 2xx:

def success?
  200 <= code && code < 300
end
Reply all
Reply to author
Forward
0 new messages