如何全局处理客户端 Blazor 应用程序的应用程序级异常?
			
			2504 次
		
2 回答
            4        
        
		
您可以创建一个处理 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 事件。
于 2019-05-23T15:08:50.957   回答
    
    
            3        
        
		
@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);
于 2020-07-13T04:13:45.937   回答