forked from GoogleCloudPlatform/microservices-demo
-
Notifications
You must be signed in to change notification settings - Fork 2
Open
Description
Issue Description
The cartservice is throwing errors in the logs related to HTTP client operations. When examining the code in src/cartservice/src/cartstore/RedisCartStore.cs
, I found that the CallExternalApiAsync()
method is missing proper error handling and is not awaited properly when called.
Problem Details
In the RedisCartStore.cs
file, line 83-102, the CallExternalApiAsync()
method is defined but has these issues:
- The method is marked as
async
but it's called without awaiting it in theAddItemAsync
method (line 79). - When making a request to the external API, there's no try-catch block to handle potential exceptions that may occur during network calls.
- The method doesn't return a Task that the caller can await.
This can cause several problems:
- Unhandled exceptions from the HTTP request
- Fire-and-forget pattern with no error handling
- Potential race conditions if the main method completes before the API call completes
Proposed Solution
- Modify the
CallExternalApiAsync()
method to include proper error handling - Ensure the method is properly awaited when called
- Add logging for better troubleshooting
private async Task CallExternalApiAsync()
{
try
{
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(mcpClientEndpoint)
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", clientEndpointBearerToken);
var response = await httpClient.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
Console.WriteLine($"External API call failed: {response.StatusCode}, Body: {responseBody}");
}
else
{
Console.WriteLine($"External API call succeeded: {responseBody}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception during external API call: {ex.Message}");
// Log but don't throw to prevent disrupting the main flow
}
}
And in the AddItemAsync
method, change:
await NotifySlackAsync(productId);
CallExternalApiAsync(); // Not awaited!
To:
await NotifySlackAsync(productId);
await CallExternalApiAsync(); // Properly awaited
Expected Outcome
This fix should prevent unhandled exceptions from the HTTP client calls and ensure that all async operations are properly awaited, which should resolve the errors seen in the logs and improve the reliability of the cartservice.
Metadata
Metadata
Assignees
Labels
No labels