For testing purpose, I would like to 'catch' any error occuring in my app and displaying it on the page (not in the console). For that purpose I discovered the ErrorBoundary component in the .Net 6 framework.
ErrorBoundaries doc from Microsoft
At first, I successfully tested this component inside a Bazor WebAssembly project.
Steps:
- Create a newBlazor WebAssembly project
- Create the component CustomErrorBoundary.razor (see code below)
- In MainLayout.razor surround the @Body instruction with the component CustomErrorBoundary
- In FetchData.razor throw an exception in the code (see below)
CustomErrorBoundary
@inherits ErrorBoundary
@if (CurrentException is null)
{
@ChildContent
}
else if (ErrorContent is not null)
{
@ErrorContent(CurrentException)
}
else
{
<div style="background-color: yellow; border: 2px dashed black; white-space: pre; font-family: consolas, monospace;">
@foreach (var exception in receivedExceptions)
{
<div class="received-exception" style="background-color: rgba(255,255,255,0.3); margin: 0.5rem; padding: 0.5rem;">
@exception.Message
</div>
}
</div>
}
@code {
List<Exception> receivedExceptions = new();
protected override Task OnErrorAsync(Exception exception)
{
receivedExceptions.Add(exception);
return base.OnErrorAsync(exception);
}
public new void Recover()
{
receivedExceptions.Clear();
base.Recover();
}
}
When testing this app and navigating in the FetchData, the error is thrown and displayed on the page.
So far so good. Now I would like to do the same but this time for a .NET Maui Blazor project.
Steps:
- Create a newBlazor .NET Maui Blazor project
- Add a the package Microsoft.AspNetCore.Components.Web to the project (to benefit from ErrorBoundary)
- Restart Visual Studio (not mandatory)
- Create the component CustomErrorBoundary.razor (see code above)
- In MainLayout.razor surround the @Body instruction with the component CustomErrorBoundary
- In WeatherForecastService.cs throw an exception in the code (see below)
Unfortunately, the project crash immeadiately when trying to start it.
So to be said simpler: it seems ErrorBoundary is not supported in a .NET Maui Blazor project.
<ErrorBoundary>
@Body
</ErrorBoundary>
The simple code above does not works in Blazor Maui.
So I don't know if ErrorBoundary is compatible with .NET Maui Blazor ? If not, how to catch any errors inside a Blazor Maui project and display it on the page ?