.NET by Patrik

Why Custom Exceptions Create Stable and Reliable APIs

Issue

Services that rely on HttpClient may expose raw exceptions such as HttpRequestException or TaskCanceledException. This forces callers to understand internal behavior and makes error handling unpredictable.

Cause

Every network error produces a different exception. Adding retry handlers or message handlers can introduce even more. When these are not wrapped or unified, the public API leaks internal implementation details.

Resolution

Wrap internal exceptions in a domain-specific exception (for example, ServiceClientException). Keep the original exception as the InnerException. This creates a predictable and stable API surface.

try
{
    var response = await _httpClient.SendAsync(request);
    response.EnsureSuccessStatusCode();
}
catch (Exception ex) when (ex is HttpRequestException ||
                           ex is TaskCanceledException ||
                           ex is OperationCanceledException)
{
    throw new ServiceClientException("Failed to execute remote request.", ex);
}

Custom exceptions protect your API and allow internal changes without breaking callers.

exceptions
design
dotnet
architecture
libraries

Comments