全局错误捕捉器

Global Error Catcher

在我的项目中,我想在数据库中记录应用程序中发生的所有错误table。我使用 try catch 块捕获了几乎所有错误,但我无法捕获 4xx 和 5xx 等全局错误。

有些情况下,应用程序不会重定向到 Startup.cs 的 Configure 方法中定义的异常处理程序,例如当我键入不存在的 url 时。

app.UseExceptionHandler("/Error");

有没有办法捕获我的应用程序中发生的所有未处理的错误?

您可以创建自己的异常过滤器,它实现 IExceptionFilter 例如:

public class GlobalExceptionFilter : IExceptionFilter
{
    ILogger<GlobalExceptionFilter> logger = null;

    public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> exceptionLogger)
    {
        logger = exceptionLogger;
    }

    public void OnException(ExceptionContext context)
    {
        // log the exception
        logger.LogError(0, context.Exception.GetBaseException(), "Exception occurred.");
    }
}

然后您可以在 ConfigureServices 方法中添加此过滤器,如下所示:

services.AddMvc(o => { o.Filters.Add<GlobalExceptionFilter>(); });

这将捕获由于请求而发生的任何未处理的异常。对于 404,您可以将以下内容添加到您的 Configure 方法中:

app.UseStatusCodePagesWithReExecute("/error/{0}");

然后您可以在 ErrorController 中记录状态代码。

有关详细信息,请参阅 Introduction to Error Handling in ASP.NET Core