Skip to content

[Blazor] Handle Errors - misleading examples on DispatchExceptionAsync (net8) #31765

@hakenr

Description

@hakenr

@guardrex I believe the TimerService.cs + Notifications.razor example on DispatchExceptionAsync in Handle errors - Handle caught exceptions outside of a Razor component's lifecycle section is wrong.

Following the article's guidance (and the readily available example in the blazor-samples repo and easily applicable there), the exception added to TimerService.cs is reported to the user even without adding the try-catch and DispatchExceptionAsync(ex) to OnNotify method.

  • This happens due to the await Timer.Start() call in StartTimer() method, where the exception from the timer loop gets propagated to Blazor
    private async Task StartTimer()
    {
        await Timer.Start();
    }
  • Changing this method to a fire-and-forget approach causes exceptions not to be reported to the user
    private void StartTimer()
    {
        _ = Timer.Start();
    }

Unfortunately, adding a try-catch block to the OnNotify() method as suggested does not effectively capture or handle exceptions, since the try block does not encompass the potential source of the exception (either directly or by capturing exceptions from the task where they occur). Incorporating this try-catch into the modified example above does not route exceptions to the previously added ErrorBoundary as expected.

I can work on creating a functional example that incorporates DispatchExceptionAsync(ex); based on the TimerService.cs and Notifications.razor if that would help. However, I'd appreciate it if you could first validate the concerns I've outlined above.

Page URL

https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/handle-errors?view=aspnetcore-8.0#handle-caught-exceptions-outside-of-a-razor-components-lifecycle

Content source URL

https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/blazor/fundamentals/handle-errors.md

Document ID

66a0b1c2-c45c-98ca-9808-6f340a861c44

Article author

@guardrex

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions