全局错误捕捉器 [英] Global Error Catcher
问题描述
在我的项目中,我想将应用程序中发生的所有错误记录在数据库表中.我使用try catch块捕获了几乎所有错误,但无法捕获4xx和5xx之类的全局错误.
In my project I want to log all the errors happen in the application in a database table. I catch almost all errors using try catch blocks, but I cannot catch the global errors like 4xx and 5xx.
在某些情况下,例如当我键入不存在的url时,应用程序不会重定向到Startup.cs的Configure方法中定义的异常处理程序.
There are cases that the application does not redirect to the Exception Handler defined in the Configure method of the Startup.cs like when I type a url which does not exist.
app.UseExceptionHandler("/Error");
是否可以捕获应用程序中发生的所有未处理的错误?
Is there a way to catch all the unhandled errors occurred in my application?
推荐答案
You could create your own Exception filter, which implements IExceptionFilter
e.g.:
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
方法中添加此过滤器:
You can then add this filter in your ConfigureServices
method as follows:
services.AddMvc(o => { o.Filters.Add<GlobalExceptionFilter>(); });
这将捕获由于请求而发生的任何未处理的异常.对于404,您可以将以下内容添加到您的Configure
方法中:
This will catch any unhanded exceptions that occur as the result of a request. For 404s you can add the following to your Configure
method:
app.UseStatusCodePagesWithReExecute("/error/{0}");
然后您可以在ErrorController
中记录状态代码.
You can then log the status code in your ErrorController
.
有关更多信息,请参见 ASP中的错误处理简介. NET核心
For further information see Introduction to Error Handling in ASP.NET Core
这篇关于全局错误捕捉器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!