在ASP.NET Core 3.1中处理未处理的异常 [英] Processing unhandled exceptions in ASP.NET Core 3.1

查看:689
本文介绍了在ASP.NET Core 3.1中处理未处理的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.NET Core 3.1中,添加了一项功能,可以将未处理的异常传递到ILogger实例,如下所示:
登录.NET Core和ASP.NET Core

In ASP.NET Core 3.1 a feature was added where unhandled exceptions can be passed onto an instance of ILogger as noted here: Logging in .NET Core and ASP.NET Core

我有一个服务器端Blazor网站,希望在其中处理这些异常,并将其记录到数据库或发送电子邮件中。但是,根据提供的文档,我无法提出实现此目的的代码。有人可以提供示例代码来捕获未处理的异常吗?

I have a Server side Blazor website where I want to be able to process these exceptions in a function where I can log them to a database or perhaps send an email. However I am unable to come up with code to do this based on the provided documentation. Could someone provide sample code to trap unhandled exceptions?

推荐答案

做些事情,我发现了一种无需进行错误记录的方法使用第三方工具。这是我的代码:

Doing some playing around, I found a way to do error logging without having to use a third party tool. Here is my code:

  public class ExceptionLogger : ILogger
  {
    public IDisposable BeginScope<TState>(TState state)
    {
      return null;
    }

    public bool IsEnabled(LogLevel logLevel)
    {
      return logLevel == LogLevel.Error;
    }

    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
    {
      if (logLevel == LogLevel.Error)
      {
        while (exception.InnerException != null)
          exception = exception.InnerException;

        LogException(exception);
      }
    }

    private void LogException(Exception error)
    {
      ...
    }


  public sealed class ExceptionLoggerProvider : ILoggerProvider
  {

    public ILogger CreateLogger(string categoryName)
    {
      return new ExceptionLogger();
    }

    public void Dispose()
    {
    }
  }

,然后在Startup.cs中添加以下内容:

And in Startup.cs add this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
  loggerFactory.AddProvider(new ExceptionLoggerProvider());
  ...

这篇关于在ASP.NET Core 3.1中处理未处理的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆