Blazor client-side Application level exception handling

蓝咒 提交于 2020-07-20 10:52:09

问题


How to globally handle application level exceptions for client-side Blazor apps?


回答1:


You can create a singleton service that handles the WriteLine event. This will be fired only on errors thanks to 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);
    }
}

You then add it to the Startup.cs file in the ConfigureServices function:

services.AddSingleton<ExceptionNotificationService>();

To use it you just subscribe to the OnException event in your main view.

Source




回答2:


@Gerrit's answer is not up to date. Now you should use ILogger for handling unhandled exception.

My example

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


来源:https://stackoverflow.com/questions/56267387/blazor-client-side-application-level-exception-handling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!