Blazor client-side Application level exception handling

You can create a singleton service that handles the WriteLine event. This will be fired only on errors thanks to Console.SetError(this);

public class ExceptionNotificationService : TextWriter
{
    private TextWriter _decorated;
    public override Encoding Encoding => Encoding.UTF8;

    public event EventHandler<string> OnException;

    public ExceptionNotificationService()
    {
        _decorated = Console.Error;
        Console.SetError(this);
    }

    public override void WriteLine(string value)
    {
        OnException?.Invoke(this, value);

        _decorated.WriteLine(value);
    }
}

You then add it to the Startup.cs file in the ConfigureServices function:

services.AddSingleton<ExceptionNotificationService>();

To use it you just subscribe to the OnException event in your main view.

Source


@Gerrit's answer is not up to date. Now you should use ILogger for handling unhandled exception.

My example

public interface IUnhandledExceptionSender
{
    event EventHandler<Exception> UnhandledExceptionThrown;
}

public class UnhandledExceptionSender : ILogger, IUnhandledExceptionSender
{

    public event EventHandler<Exception> UnhandledExceptionThrown;

    public IDisposable BeginScope<TState>(TState state)
    {
        return null;
    }

    public bool IsEnabled(LogLevel logLevel)
    {
        return true;
    }

    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state,
        Exception exception, Func<TState, Exception, string> formatter)
    {            
        if (exception != null)
        {                
            UnhandledExceptionThrown?.Invoke(this, exception);
        }            
    }
}

Program.cs

var unhandledExceptionSender = new UnhandledExceptionSender();
var myLoggerProvider = new MyLoggerProvider(unhandledExceptionSender);
builder.Logging.AddProvider(myLoggerProvider);
builder.Services.AddSingleton<IUnhandledExceptionSender>(unhandledExceptionSender);