Error handling
An HTTP error throws ApiException. A failed connection throws TransporterException. Every exception the SDK throws implements IdealPostcodesException.
What does an ApiException contain?
ApiException carries the HTTP status, the API error code and the decoded body.
| Member | Contents |
|---|---|
getStatusCode() | HTTP status, such as 404 |
getCode() | API error code, such as 4040. 0 when the body carries none |
getMessage() | API error message, or the HTTP reason phrase |
getBody() | Decoded JSON body as an array, or the raw text when it is not JSON |
getResponse() | The PSR-7 response |
use IdealPostcodes\Exceptions\ApiException;
use IdealPostcodes\IdealPostcodes;
$client = IdealPostcodes::client('ak_test');
try {
$response = $client->postcodes('BR8 7RV');
print_r($response->result);
} catch (ApiException $e) {
if ($e->getCode() === 4040) {
echo 'Postcode not found. Try: ', implode(', ', $e->getBody()['suggestions']), PHP_EOL;
} else {
echo $e->getStatusCode(), ' ', $e->getCode(), ' ', $e->getMessage(), PHP_EOL;
}
}
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 throwing. See postcode lookup.
Which other exceptions can the SDK throw?
| Exception | When |
|---|---|
TransporterException | The PSR-18 client could not complete the request: DNS, connection, TLS or timeout failure. The client's own exception is getPrevious() |
UnserializableResponse | A success response whose body is not a JSON object |
MissingManagementKey | A key, licensee or configuration operation on a client with no Management Key. Thrown before any request is sent |
MissingResponseField | A success response without a field the SDK requires. getMessage() names the field and $type the class. Report it to support: the API and the SDK disagree |
How do I catch everything from the SDK?
Catch IdealPostcodesException. It is an interface every SDK exception implements, so one catch covers API errors, transport failures and configuration mistakes.
use IdealPostcodes\Exceptions\IdealPostcodesException;
try {
$response = $client->findAddress(['query' => '9 Malyons Road']);
} catch (IdealPostcodesException $e) {
error_log($e->getMessage());
}
How do I tell a timeout from a connection failure?
Both throw TransporterException. The cause is the HTTP client's own exception in getPrevious(). With Guzzle, a timeout and a refused connection both arrive as GuzzleHttp\Exception\ConnectException, with the detail in its message.