Error handling
An HTTP error throws ApiException. Every exception the SDK defines derives from IdealPostcodesException. Connection failures, timeouts and cancellation throw the standard .NET exceptions, as any HttpClient call does.
ApiException
ApiException carries the HTTP status, the API error code and the body.
| Member | Contents |
|---|---|
StatusCode | HTTP status, such as HttpStatusCode.NotFound |
Code | API error code, such as 4040. 0 when the body carries none |
Message | API error message, or the HTTP reason phrase |
Body | The response body as sent |
Errors.cscsharp
using IdealPostcodes;
using var client = new IdealPostcodesClient("ak_test");
try
{
var response = await client.PostcodesAsync("BR8 7RV");
Console.WriteLine(response.Result.Count);
}
catch (ApiException e) when (e.Code == 4040)
{
Console.WriteLine("Postcode not found");
}
catch (ApiException e)
{
Console.WriteLine($"{(int)e.StatusCode} {e.Code} {e.Message}");
}
The error codes guide lists each code and how to fix it. For postcode lookups, LookupAsync() handles the 4040 case for you and returns the suggestions instead of throwing. See postcode lookup.
Other exceptions
| Exception | When |
|---|---|
UnserializableResponseException | A success response whose body is not a JSON object, such as an HTML page from a proxy. Body holds it as sent and InnerException the JsonException, if any |
MissingManagementKeyException | A key, licensee or configuration operation on a client with no Management Key. Thrown before any request is sent |
HttpRequestException | The request could not complete: DNS, connection or TLS failure |
TaskCanceledException | The HttpClient timed out. On .NET 5 and later its InnerException is a TimeoutException |
OperationCanceledException | Your CancellationToken was cancelled |
ArgumentException | A client created without an API key, or a required argument passed as null |
Catch every SDK error
Catch IdealPostcodesException for API errors and SDK mistakes, and HttpRequestException for the network.
CatchAll.cscsharp
try
{
var response = await client.FindAddressAsync(new FindAddressParams { Query = "9 Malyons Road" });
}
catch (IdealPostcodesException e)
{
Console.Error.WriteLine(e.Message);
}
catch (HttpRequestException e)
{
Console.Error.WriteLine($"Network: {e.Message}");
}