Global Error Catcher

戏子无情 提交于 2019-12-07 02:46:31

问题


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.

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?


回答1:


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.");
    }
}

You can then add this filter in your ConfigureServices method as follows:

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

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

You can then log the status code in your ErrorController.

For further information see Introduction to Error Handling in ASP.NET Core



来源:https://stackoverflow.com/questions/48578065/global-error-catcher

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