Error Handling

Due to the “multiple requests” support, httpx chooses not to raise exceptions. A call to HTTPX will therefore always return a response. However, the response might be an error response (of the class HTTPX::ErrorResponse):

response = HTTPX.get("")
puts response.class #=> "HTTPX::Response"

response = HTTPX.get("")
puts response.class #=> "HTTPX::ErrorResponse"


(since v0.18.0)

A simple strategy is to query the response for an error:

response = HTTPX.get("")
if response.error #=> yes, it's `Errno::CONNREFUSED`
  # ...

response = HTTPX.get("") #=> 404
if response.error #=> yes, it's `HTTPX::HTTPError`
  # ...

response = HTTPX.get("") #=> 200
if response.error #=> no, it's `nil`


(since v0.0.3)

You can choose to bubble up such exceptions by calling response.raise_for_status. This will raise an exception if the response wraps an exception or if the response contains an HTTP Error Status Code (4xx or 5xx).

response = HTTPX.get("")
response.raise_for_status #=> raises Errno::CONNREFUSED

response = HTTPX.get("") #=> 404
response.raise_for_status #=> raises HTTPX::HTTPError

response = HTTPX.get("") #=> 200
response.raise_for_status #=> nil

pattern-matching on errors

As of version 0.15.0, you can use pattern-matching (note: ruby 3 only) to check for errors:

case (response = HTTPX.get(""))
in {status: 200..299}
  # success
in {status: 400..}
  # http error
in {error: error}
  puts error.class #=> "Errno::CONNREFUSED"

Next: Internationalized Domain Names