【问题标题】:Blazor client-side Application level exception handlingBlazor 客户端应用程序级异常处理
【发布时间】:2019-10-09 13:34:42
【问题描述】:

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

【问题讨论】:

    标签: exception blazor blazor-client-side


    【解决方案1】:

    您可以创建一个处理 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>();
    

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

    Source

    【讨论】:

    • 不幸的是,我无法让它工作。这应该捕获哪些类型的异常?
    • 这会捕获通常会在浏览器控制台中引发错误的所有内容。按照它的设置方式,这些错误仍会显示在控制台中,但您可以根据需要对它们进行操作或记录它们。哪个部分不完全工作?您是否确定在代码中的某处订阅了 OnException 事件?你可以在里面放一些 console.writelines 看看有没有什么东西被抓到了。
    【解决方案2】:

    @Gerrit 的回答不是最新的。现在您应该使用 ILogger 来处理未处理的异常。

    我的例子

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

    程序.cs

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-18
      • 2018-12-10
      • 2014-04-15
      • 1970-01-01
      • 2019-07-27
      • 2015-04-26
      • 1970-01-01
      相关资源
      最近更新 更多