How to Implement Global Exception Handling in ASP.NET Core Application

How to Implement Global Exception Handling in ASP.NET Core Application

In this tutorial, we will learn how to implement global exception handling in an ASP.NET Core application. Exception handling is one of the important features of any application, it is considered as a powerful mechanism to handle the runtime errors that may occur during the execution time of the application and without it we can't maintain the normal behavior of the web application. Therefore, we should always make sure to implement exception handling in a proper way.

In ASP.NET Core, we should implement the exception handling for every action and we should provide a meaningful message to the user about the issue rather than a system generated message, which may not be understandable to a user. However, in some cases we may face global errors in the application that are not handled at the action level, for this reason, we can implement the global exception handling so that all types of unhandled exceptions can be caught in this handler. The benefit of implementing a global exception handler is that we need define this block of code in one place. Through this handler, any exception that occurs in our application will be handled, even in new methods or controllers. This concept of global exception handling can be applied as well in the ASP.NET Core Web API.

Implementing Global Exception Handling in ASP.NET Core

The first step in this tutorial is to create an ASP.NET Core Web Project in Visual Studio (I'm using Visual Studio Community 2022). Let's apply the following steps:

  • Open the Microsoft Visual Studio and Click on Create a New Project
  • In the Create New Project dialog box, select ASP.NET Core Web App for C# and then click on the Next Button.

Implement Global Exception Handling In ASP.NET Core Web App

  • In the Configure your new project window, provide the project name and then click on the Create button
  • In the additional information select .NET 6 for the framework. then click Create button
  • Ensure that the checkboxes “Enable Docker Support” is unchecked. We won’t be using Docker in this tutorial
  • Ensure that “Authentication Type” is "None" as we won’t be using authentication either.
  • Click Create

Create a New ASP.NET Core Web - .NET 6

Use the UseExceptionHandler Middleware in ASP.NET Core

To implement the global exception handler, we can make use of the ASP.NET Core built-in Middleware. A middleware is mainly a component injected into the request processing pipeline which handles the requests and responses. We can use the ASP.NET Core built-in middleware UseExceptionHandler to implement the global exception handler. The ASP.NET Core request processing pipeline includes a chain of middleware components. This pipeline in turn contains a series of request delegates that are invoked one after another. While the incoming requests flow through each of the middleware components in the pipeline, each of these components can either process the request or pass the request to the next component in the pipeline.

The UseExceptionHandler is enabled by default in the Program.cs file. Otherwise, you can enable it by adding the following code syntax:

app.UseExceptionHandler("/Home/Error");

In order to capture the details of the exception objects – i.e. like the stack trace, message, we must set the following options in the exception handler:

app.UseExceptionHandler(
        options =>
        {
            options.Run(
                async context =>
                {
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    context.Response.ContentType = "text/html";
                    var exceptionObject = context.Features.Get<IExceptionHandlerFeature>();
                    if (null != exceptionObject)
                    {
                        var errorMessage = $"<b>Exception Error: {exceptionObject.Error.Message} </b> {exceptionObject.Error.StackTrace}";
                        await context.Response.WriteAsync(errorMessage).ConfigureAwait(false);
                    }
                });
        }
    );
You can notice in the preceding code we are formatting the exception message and we are writing the output in the response of the request. As an alternative you can log this message in the log file using NLog or any other third party library.

In this post, we configured the global exception handling in ASP.NET Core Web Application by modifying the Program.cs class.



Post a Comment

Previous Post Next Post