Skip to content

Commit

Permalink
Update Readme with Exception Handling
Browse files Browse the repository at this point in the history
  • Loading branch information
sashirestela committed Dec 14, 2024
1 parent eca27a1 commit 7546858
Showing 1 changed file with 122 additions and 0 deletions.
122 changes: 122 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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<String, List<String>> 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<CleverClientException> 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:
Expand Down

0 comments on commit 7546858

Please sign in to comment.