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

Blazor client-side Application level exception handling

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

您可以创建处理 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

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

Program.cs

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