Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Error Catcher

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?

like image 721
pitaridis Avatar asked Feb 02 '18 07:02

pitaridis


People also ask

How is global error handling implemented?

Global Error Handler This method is called whenever an error is thrown somewhere in the application. The error is passed as a parameter and can be processed further inside the method. In our case a dialog is opened where the error message should be displayed and the error is logged to the browser console.

How does Web API handle global exception in .NET core?

The middleware UseExceptionHandler can be used to handle exceptions globally. You can get all the details of the exception object (Stack Trace, Inner exception, message etc..) and display them on-screen. You can implement like this.

What is global exception handling in C#?

An ExceptionFilterAttribute is used to collect unhandled exceptions. You can register it as a global filter, and it will function as a global exception handler. Another option is to use a custom middleware designed to do nothing but catch unhandled exceptions.


1 Answers

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

like image 137
SpruceMoose Avatar answered Oct 22 '22 10:10

SpruceMoose