Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I would like to be able to catch all unhandled exceptions in one single place building a Blazor single page application. Like using the "Current.DispatcherUnhandledException" in WPF applications.

This question is exclusively about client-side (webassembly) exception handling. I am using Blazor version 3.0.0-preview8.19405.7

I have been searching for a solution, but it seems like it does not exist. On Microsofts documentation (https://docs.microsoft.com/en-us/aspnet/core/blazor/handle-errors?view=aspnetcore-3.0) there is a list of places errors may occur and a walk through on how to handle each one of them. It believe there must be a more bullet proof way to catch all.

like image 785
TroelsGP Avatar asked Aug 17 '19 19:08

TroelsGP


1 Answers

In .NET 6 there is component called ErrorBoundary.

<ErrorBoundary>
   @Body
</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)
like image 140
Alamakanambra Avatar answered Oct 11 '22 19:10

Alamakanambra