Search code examples
.neterror-handlingblazorblazor-server-side

.NET and Blazor 8 - handling exceptions without ErrorBoundary on Interactive Server pages?


I have a Blazor & .NET 8 Web App which uses interactive server mode to render its pages.

Is it possible to add a global handler which will catch unhandled exceptions before the default yellow "An error has occurred. reload" error message is displayed?

I do believe I can achieve this with ErrorBoundary but have been asked to investigate and consider other options as well, for flexibility's sake.

I looked into middleware, tried the code below (taken from UseExceptionHandler Blazor server-side not working) and it doesn't work. I expect this is for the same reason as the most upvoted answer in the linked question.

If the ErrorBoundary (or deriving from ErrorBoundary) is the only way to catch all unhandled exceptions thrown as a result of user action in ISR, please state that categorically.

Here is my middleware handler.

public class ExceptionHandlingMiddleware
{
    private readonly RequestDelegate _next;
    private string _path;
    private readonly ILogger<ExceptionHandlingMiddleware> _logger;

    public ExceptionHandlingMiddleware(ILogger<ExceptionHandlingMiddleware> logger, RequestDelegate next, string path)
    {
        _next = next;
        _path = path;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (System.Exception ex)
        {
            _logger.LogError(ex, "Failed to invoke {Message}", ex.Message);
            context.Response.Redirect(_path);
        }
    }
}

Solution

  • In my opinion, the ErrorBoundary component is a recommended approach for catching unhandled exceptions in Blazor components. As you noticed, the middleware code won't catch exceptions thrown during the rendering of components because these exceptions occur outside the HTTP request pipeline, which the middleware is designed to handle.

    ErrorBoundary is designed for Blazor's component model, allowing you to handle errors by displaying a custom error UI instead of the default yellow error message. This will help you provide user-friendly applications, even when unexpected errors occur. By using ErrorBoundary you can customize the error UI to match your application's design and even log errors or perform other actions before rendering the error message.

    While there are other ways, such as global exception handling in Program.cs or using CircuitHandler, these are not effective for catching exceptions during component rendering. It is more suitable for handling broader application-level events.

    For more details, you can refer to the official documentation on error handling in Blazor.