【发布时间】:2019-10-09 13:34:42
【问题描述】:
如何全局处理客户端 Blazor 应用的应用级异常?
【问题讨论】:
标签: exception blazor blazor-client-side
如何全局处理客户端 Blazor 应用的应用级异常?
【问题讨论】:
标签: exception blazor blazor-client-side
您可以创建一个处理 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 事件。
【讨论】:
@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);
【讨论】: