Skip to content

Fix JSON deserialization error in LoadProductDataAsync when product data source is unavailable#87

Merged
markjbrown merged 2 commits intostartfrom
copilot/fix-webfrontend-errors
Oct 15, 2025
Merged

Fix JSON deserialization error in LoadProductDataAsync when product data source is unavailable#87
markjbrown merged 2 commits intostartfrom
copilot/fix-webfrontend-errors

Conversation

Copy link
Contributor

Copilot AI commented Oct 14, 2025

Problem

The web application was crashing during initialization with a JsonException when the product data source was unavailable or returned empty content. This occurred in the LoadProductDataAsync() method in SemanticKernelService.cs at line 260.

The error manifested as:

System.Text.Json.JsonException: The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0.

This happened because the code attempted to deserialize an empty string when:

  • The HTTP request to fetch product data failed
  • The product data source URL was unreachable
  • The HTTP response was unsuccessful but returned empty content

Solution

Added comprehensive error handling to the LoadProductDataAsync() method:

  1. HTTP request error handling - Wrapped the HTTP call in a try-catch block to handle network failures and log meaningful error messages
  2. Response validation - Check if the HTTP response is successful before reading content
  3. Empty content validation - Verify that JSON content is not null or whitespace before attempting deserialization
  4. JSON deserialization error handling - Catch JsonException with a descriptive error message
  5. Null/empty product list validation - Ensure the deserialized product list contains data

All error cases now return gracefully with informative console logging, allowing the application to start successfully even when product data is unavailable. This is particularly important for local development scenarios where external data sources may not be accessible.

Changes Made

  • Modified SemanticKernelService.cs:
    • Added try-catch around HTTP GET request
    • Added validation for HTTP response status
    • Added validation for empty/null JSON content
    • Added try-catch around JSON deserialization
    • Added validation for null/empty product list
    • Improved error messages for debugging

The application now handles missing product data gracefully instead of crashing, improving the developer experience and resilience of the application.

Original prompt

This section details on the original issue you should resolve

<issue_title>webfrontend Errors</issue_title>
<issue_description>Web app no longer functioning for me. Unsure when it was last working. I last ran it months ago.
When running it locally, webfrontend runs into errors and is unusable.

Image Image

Console error

blazor.server.js:1 [2025-10-14T19:43:25.966Z] Information: Normalizing '_blazor' to 'http://localhost:8100/_blazor'.
blazor.server.js:1 [2025-10-14T19:43:26.004Z] Information: WebSocket connected to ws://localhost:8100/_blazor?id=5bkAoTpm-zZg8xwPOUtg_g.
blazor.server.js:1 [2025-10-14T19:43:44.418Z] Error: System.Text.Json.JsonException: The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
---> System.Text.Json.JsonReaderException: The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. LineNumber: 0 | BytePositionInLine: 0.
at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan1 bytes) at System.Text.Json.Utf8JsonReader.Read() at System.Text.Json.Serialization.JsonConverter1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
--- End of inner exception stack trace ---
at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& state, JsonReaderException ex)
at System.Text.Json.Serialization.JsonConverter1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) at System.Text.Json.Serialization.Metadata.JsonTypeInfo1.Deserialize(Utf8JsonReader& reader, ReadStack& state)
at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan1 utf8Json, JsonTypeInfo1 jsonTypeInfo, Nullable1 actualByteCount) at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan1 json, JsonTypeInfo`1 jsonTypeInfo)
at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)
at Cosmos.Copilot.Services.SemanticKernelService.LoadProductDataAsync() in C:\Users\Admin\Repos\cosmosdb-nosql-copilot\src\cosmos-copilot.WebApp\Services\SemanticKernelService.cs:line 260
at Cosmos.Copilot.Services.ChatService.InitializeAsync() in C:\Users\Admin\Repos\cosmosdb-nosql-copilot\src\cosmos-copilot.WebApp\Services\ChatService.cs:line 120
at Cosmos.Copilot.Pages.ChatPane.OnInitializedAsync() in C:\Users\Admin\Repos\cosmosdb-nosql-copilot\src\cosmos-copilot.WebApp\Pages\ChatPane.razor:line 285
at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
log @ blazor.server.js:1
blazor.server.js:1 [2025-10-14T19:43:44.419Z] Information: Connection disconnected.


Error in Structured logs

False MSAL 4.65.0.0 MSAL.NetCore .NET 8.0.4 Microsoft Windows 10.0.22621 [2025-10-08 20:03:53Z - a6ddc548-2b3a-4862-add5-9742e3c66a7f] Exception type: Azure.Identity.CredentialUnavailableException
---> Inner Exception Details
Exception type: Azure.RequestFailedException
---> Inner Exception Details
Exception type: System.Net.Http.HttpRequestException
---> Inner Exception Details
Exception type: System.Net.Sockets.SocketException
To see full exception details, enable PII Logging. See https://aka.ms/msal-net-logging
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)
at System.Net.Sockets.Socket.g__WaitForConnectWithCancellation|285_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)

=== End of inner exception stack trace ===
To see full exception details, enable PII Logging. See https://aka.ms/msal-net-logging
at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellation...

Fixes #86


💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.

…ation errors

Co-authored-by: markjbrown <800166+markjbrown@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix webfrontend errors for better usability Fix JSON deserialization error in LoadProductDataAsync when product data source is unavailable Oct 14, 2025
Copilot AI requested a review from markjbrown October 14, 2025 23:01
@markjbrown markjbrown marked this pull request as ready for review October 15, 2025 02:08
@markjbrown markjbrown merged commit 9c49ca2 into start Oct 15, 2025
4 checks passed
Copilot AI mentioned this pull request Oct 15, 2025
4 tasks
Copilot AI added a commit that referenced this pull request Oct 15, 2025
Co-authored-by: markjbrown <800166+markjbrown@users.noreply.github.com>
markjbrown added a commit that referenced this pull request Oct 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants