Search code examples
exceptionblazorblazor-client-side

Blazor client-side Application level exception handling


How to globally handle application level exceptions for client-side Blazor apps?


Solution

  • 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