aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

"network error" - unhandled exception - Blazor WASM - Streaming http requests from IAsyncEnumerable api endpoint

Open radderz opened this issue 8 months ago • 5 comments

Is there an existing issue for this?

  • [X] I have searched the existing issues

Describe the bug

When using IAsyncEnumerable<T> response type from an asp.net core API and using WebAssemblyEnableStreamingResponse if there is a network error, an unhandled exception is thrown outside of the caller scope.

i.e. there is no way to catch the error and this ends up displaying a Blazor UI error that cannot be controlled. It doesn't break anything and the site just continues working, but the error shows up in the console and shows an error popup on the UI.

A try catch around this doesn't suppress the error.

try
{
	using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, $"/api/xxxxxxx");

	request.Options.Set(new HttpRequestOptionsKey<bool>("WebAssemblyEnableStreamingResponse"), true);

	using var httpClient = HttpClientFactory.CreateClient("Platform.Api");
	httpClient.Timeout = TimeSpan.FromHours(2);
	using HttpResponseMessage response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token);

	response.EnsureSuccessStatusCode();

	using Stream responseStream = await response.Content.ReadAsStreamAsync(token);

	var stateEnumerable = (IAsyncEnumerable<List<AssetState>>)JsonSerializer.DeserializeAsyncEnumerable<List<AssetState>>(
			responseStream,
			_jsonSerializerOptionsStreaming,
			token
		);

	await foreach (List<AssetState> assetStateBatch in stateEnumerable)
	{
	}
}
catch (OperationCanceledException)
{
	// do nothing, cancelled.
}
catch (Exception err)
{
	Console.WriteLine("StreamAssetStates - Exception: {0}", err);
}

The below image shows the error in the console, you can see the console write line in between from the catch, but there is still an unhandled error outside the scope.

image

Expected Behavior

  • No unhandled exception outside of the scope of the caller, so that the callers Try Catch statements can handle the error.
  • No Blazor Error UI popup

Steps To Reproduce

The steps are a reasonably simple but the blazor UI needs to be connected to an api with the ability to remove connectivity (i.e. pulling out the network cable or disconnect wifi). So the api needs to be on a different machine or be isolatable from the browser running the blazor wasm UI. Possibly devtunnels would make this easy to reproduce.

  1. Run an API with an IAsyncEnumerable endpoint that runs forever
  2. Run client connected to this endpoint on a different host
  3. Disconnect/break the network connection between the browser and the api to trigger a network error

Exceptions (if any)

Error in http_wasm_abort_response: TypeError: network error

.NET Version

8.0.300

Anything else?

No response

radderz avatar May 30 '24 23:05 radderz