Error handling
An HTTP error raises IdealPostcodes::ApiError. A failed connection raises IdealPostcodes::TransportError. Every error the SDK raises inherits from IdealPostcodes::Error.
ApiError
ApiError carries the HTTP status, the API error code and the decoded body.
| Reader | Contents |
|---|---|
status | HTTP status, such as 404 |
code | API error code, such as 4040. nil when the body carries none |
message | API error message, or HTTP <status> when the body carries none |
body | Decoded JSON body as a hash, or the raw text when it is not JSON |
require "ideal_postcodes"
client = IdealPostcodes::Client.new(api_key: "ak_test")
begin
response = client.postcodes("BR8 7RV")
response.result.each { |address| puts address.line_1 }
rescue IdealPostcodes::ApiError => e
if e.code == 4040
puts "Postcode not found. Try: #{e.body['suggestions'].join(', ')}"
else
puts "#{e.status} #{e.code} #{e.message}"
end
end
The error codes guide lists each code and how to fix it. For postcode lookups, lookup handles the 4040 case for you and returns the suggestions instead of raising. See postcode lookup.
Other errors
| Error | When |
|---|---|
TransportError | No response arrived: DNS, connection, TLS or timeout failure. The original exception is cause |
UnserializableResponseError | A success response whose body is not a JSON object. response holds it |
MissingManagementKeyError | A key, licensee or configuration operation on a client with no Management Key. Raised before any request is sent |
A keyword the method does not take raises Ruby's own ArgumentError, before any request.
Catch every SDK error
Rescue IdealPostcodes::Error. Every SDK error inherits from it, so one rescue covers API errors, transport failures and configuration mistakes.
begin
client.find_address(query: "9 Malyons Road")
rescue IdealPostcodes::Error => e
warn e.message
end
Timeouts and connection failures
Both raise TransportError. Check its cause: a timeout is a Net::OpenTimeout or Net::ReadTimeout, and a refused connection an Errno::ECONNREFUSED.