Skip to main content

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.

MemberContents
StatusCodeHTTP status, such as HttpStatusCode.NotFound
CodeAPI error code, such as 4040. 0 when the body carries none
MessageAPI error message, or the HTTP reason phrase
BodyThe 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​

ExceptionWhen
UnserializableResponseExceptionA 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
MissingManagementKeyExceptionA key, licensee or configuration operation on a client with no Management Key. Thrown before any request is sent
HttpRequestExceptionThe request could not complete: DNS, connection or TLS failure
TaskCanceledExceptionThe HttpClient timed out. On .NET 5 and later its InnerException is a TimeoutException
OperationCanceledExceptionYour CancellationToken was cancelled
ArgumentExceptionA 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}");
}