Is there a way to globally catch all unhandled errors in a Blazor single page application?

In .NET 6 there is component called ErrorBoundary.

Simple example:

<ErrorBoundary>
   @Body
</ErrorBoundary>

Advanced Example:

 <ErrorBoundary>
    <ChildContent>
          @Body
    </ChildContent>
    <ErrorContent Context="ex">
          @{ OnError(@ex); } @*calls custom handler*@
          <p>@ex.Message</p> @*prints exeption on page*@
    </ErrorContent>
 </ErrorBoundary>

For the global exception handling I see this as an option:
Create CustomErrorBoundary (inherit the ErrorBoundary) and override the OnErrorAsync(Exception exception).

Here is the sample of CustomErrorBoundary.

Useful links

  • Official docs
  • Some info in .NET 6 preview 4 blog post.
  • Tests for ErrorBoundary in dotnet repo (great sample).
  • PR on dotnet repo.
  • Simple usage of ErrorBoundary (youtube)

Leave a Comment