代码之家  ›  专栏  ›  技术社区  ›  AlvinfromDiaspar

Blazor客户端应用程序级异常处理

  •  0
  • AlvinfromDiaspar  · 技术社区  · 7 年前

    如何全局处理客户端Blazor应用程序的应用程序级异常?

    0 回复  |  直到 6 年前
        1
  •  4
  •   Gerrit    7 年前

    您可以创建一个处理WriteLine事件的单例服务。由于以下原因,这将仅在出现错误时触发 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);
        }
    }
    

    然后将其添加到ConfigureServices函数中的Startup.cs文件中:

    services.AddSingleton<ExceptionNotificationService>();
    

    要使用它,您只需在主视图中订阅OneException事件。

    Source

        2
  •  3
  •   3per    6 年前

    我的例子

    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);
            }            
        }
    }
    

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