In Blazor Server webapp, I click on a link that leads to a page and that page uses an IAbcApiClient. During resolving the dependency injection of IAbcApiClient, it threw an error (e.g. invalid URI). So the blazor circuit breaks and the UI is stuck. How to handle it in such a way that user is not stuck in that page and still be able to see a friendly error message or perhaps redirect to error page?
Putting the try catch here in Program.cs did not work since this is just registering service and not resolving DI yet. AddApiClients is where it calls AddHttpClient and set the client baseaddress. I know I can ensure that baseaddress should be correct to avoid this from happening. But I am curious that what if in the future, if there are unexpected dependency injection errors, how to handle it the best way in blazor for these kind of situations.
Program.cs
builder.Services.AddApiClients(builder.Configuration);
I have Custom circuit handler which logs the error but still the UI is stuck due to circuit break.
public class CustomCircuitHandler : CircuitHandler
{
private readonly ILogger<CustomCircuitHandler> _logger;
public CustomCircuitHandler(ILogger<CustomCircuitHandler> logger)
{
_logger = logger;
}
public override Task OnConnectionDownAsync(Circuit circuit, CancellationToken cancellationToken)
{
_logger.LogError("Circuit {circuitId} connection lost.", circuit.Id);
return Task.CompletedTask;
}
}
I already have errorboundary in mainlayout already but it is not caught there.
If I manually enter the URL of that page in the browser and press enter, it redirects me to error page via this code below, which is good.
app.UseExceptionHandler(errorApp =>
{ errorApp.Run(async context =>
{ //redirect to error page }) })
The connection disconnected, So you cannot redirect from serverside. The only way to do it is using clientside, such as something listening to the blazor websocket connectionstate. However, as far as i know, there isn't a built in way to do this https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/signalr?view=aspnetcore-9.0. I have a workaround here you can reference.
Add following code to App.razor
<script src="_framework/blazor.web.js"></script>
<script>
const checkElementStyle = () => {
const element = document.getElementById('blazor-error-ui');
if (element && element.style.display === 'block') {
window.location.reload();
}
};
// Check every 100ms (you can adjust the interval)
setInterval(checkElementStyle, 100);
</script>
Explain : exception occurs, blazor-error-ui
element in mainlayout will show, then do a reload immediately.