From 7546858bf12ce7e38b32e4731eb0c245a5c774e2 Mon Sep 17 00:00:00 2001 From: Sashir Estela Date: Sat, 14 Dec 2024 17:43:41 +0000 Subject: [PATCH] Update Readme with Exception Handling --- README.md | 122 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) diff --git a/README.md b/README.md index 18d8bea..dce7772 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ Library that makes it easy to use the Java HttpClient to perform http operations - [Interface Annotations](#interface-annotations) - [Supported Response Types](#supported-response-types) - [Interface Default Methods](#interface-default-methods) + - [Exception Handling](#exception-handling) **NEW** - [Examples](#-examples) - [Contributing](#-contributing) - [License](#-license) @@ -242,6 +243,127 @@ interface Completions { Note that we have named the annotated methods with the suffix "Basic" just to indicate that we should not call them directly but should call the default ones (those without the suffix). +### Exception Handling + +The `CleverClientException` provides robust error handling mechanisms for HTTP client interactions, allowing you to capture and process different types of errors comprehensively. + +#### Key Exception Handling Scenarios + +##### 1. Basic Exception Catching + +```java +try { + // Your HTTP client method call + Response response = client.someMethod(); +} catch (CleverClientException e) { + // Handle the specific CleverClient exception + System.err.println("An error occurred: " + e.getMessage()); +} +``` + +##### 2. Accessing HTTP Response Details + +When an exception occurs during an HTTP request, you can retrieve detailed response information: + +```java +try { + // HTTP client method call + client.makeRequest(); +} catch (CleverClientException e) { + // Check if response info is available + e.responseInfo().ifPresent(responseInfo -> { + // Access status code + int statusCode = responseInfo.getStatusCode(); + System.err.println("HTTP Status Code: " + statusCode); + + // Access response headers + Map> headers = responseInfo.getHeaders(); + headers.forEach((key, value) -> + System.err.println(key + ": " + value) + ); + + // Access response data + String responseData = responseInfo.getData(); + System.err.println("Response Body: " + responseData); + + // Access request details + CleverClientException.HttpResponseInfo.HttpRequestInfo requestInfo = + responseInfo.getRequest(); + System.err.println("Request Method: " + requestInfo.getHttpMethod()); + System.err.println("Request URL: " + requestInfo.getUrl()); + }); +} +``` +##### 3. Extracting CleverClientException from Other Exceptions + +The library provides a utility method to extract `CleverClientException` from other exception types. This is the case when exceptions occurs in `CompletableFuture` processing, where a CompletionException is the outer exception and CleverClientException is the cause one: + +```java +try { + // Some method that might throw an exception + performOperation(); +} catch (Throwable e) { + // Try to extract CleverClientException + Optional cleverException = + CleverClientException.getFrom(e); + + cleverException.ifPresent(exception -> { + // Handle the CleverClientException specifically + System.err.println("Detailed HTTP Error: " + exception.getMessage()); + + // Optionally access response details + exception.responseInfo().ifPresent(responseInfo -> { + // Handle response info + }); + }); +} +``` +#### Best Practices + +- Always handle exceptions at the appropriate level of your application. +- Log detailed error information for troubleshooting. +- Use the `responseInfo()` method to get additional context about HTTP errors. +- Consider creating custom error handling logic based on specific status codes or error conditions. + +#### Example of Complex Error Handling + +```java +public void robustHttpCall() { + try { + // HTTP client method + client.executeRequest(); + } catch (CleverClientException e) { + // Comprehensive error handling + if (e.responseInfo().isPresent()) { + HttpResponseInfo info = e.responseInfo().get(); + switch (info.getStatusCode()) { + case 400: + handleBadRequest(info); + break; + case 401: + handleUnauthorized(info); + break; + case 500: + handleServerError(info); + break; + default: + handleGenericError(e); + } + } else { + // Handle exceptions without response info + handleGenericError(e); + } + } +} +``` + +#### Recommendations + +- Always use try-catch blocks when making HTTP calls +- Log errors for monitoring and debugging +- Implement specific handling for different HTTP status codes +- Use the rich error information provided by `CleverClientException` + ## ✳ Examples Some examples have been created in the folder [example](https://github.com/sashirestela/cleverclient/tree/main/src/example/java/io/github/sashirestela/cleverclient/example) and you can follow the next steps to execute them: