ASP.NET Core Exception Middleware

Handling errors is one of the most important aspect of any application. ASP.NET Core Exception Middleware provides an option to implement global exception handling logic.

ASP.NET Core has provided try, catch & finally block for exceptions handling. Instead of implementing these blocks in all the methods it is better to implement a global exception handler.

Also most of the time developers are so engrossed in the implementation of actual code logic that they tend to ignore or forget error handling code. This results in many runtime exceptions some of which get captured during testing and rest get reported on production. So global error handling logic will allow the application to gracefully log the error and report the user-friendly error message to users.

If you need details on how to implement logging in ASP.NET Core then you can check this article on ASP.NET Core Logging

ASP.NET Core Exception Middleware

ASP.NET Core provides a built-in middleware to implement global error handler but we can even implement our own custom exception middleware to handle exceptions globally. For further details on middleware, you can read this article on ASP.NET Core Middleware

Implementing ASP.NET Core Exception Middleware

Handling errors globally with built-in middleware

Built-in exception middleware can be configured in the configure method of a startup.cs file. As shown in the below code exception middleware and environment variable are used to redirect to /home/error page when an error occurs in the production environment & in the development environment it will display developer exception page which contains details for further analysis.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }
    //Remaining code was removed
}

I have simulated error condition to capture screenshots for developer exception page & custom error page for production Below is the screenshot of Developer exception page which obviously has more data for debugging & analysis.

ASP.NET Core Developer Exception Page

Shown below is the custom error page for production environment.

ASP.NET Core Use Exception Handler Page

Newsletter Subscription

Stay updated! Instantly get notified about my new articles in your mailbox by subscribing via email

Handling errors globally with custom exception middleware

Shown below is the code of custom exception middleware which in case of error will log the exception details and redirect the user to a global error page.

public class ExceptionMiddleware
{
    private readonly RequestDelegate _next;

    public ExceptionMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext httpContext)
    {
        try
        {
            await _next(httpContext);
        }
        catch (Exception ex)
        {
            //Add logging code to log exception details
            httpContext.Response.Redirect("/Home/Error");
        }
    }
}

// Extension method used to add the middleware to the HTTP request pipeline.
public static class ExceptionMiddlewareExtensions
{
    public static IApplicationBuilder UseExceptionMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<ExceptionMiddleware>();
    }
}

This custom exception middleware will be used in the ASP.NET Core middleware pipeline as shown below in code from configure method in a startup.cs file

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseStaticFiles();

    if (!env.IsDevelopment())
    {
        app.UseExceptionMiddleware();
    }
    //Remaining code was removed
}

Summary

ASP.NET Core Exception middleware can be used to implement a global exception handling code. It is always recommended to implement a global exception handler as we can control as to what to log during exception times. This will keep the code clean & readable.

References: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-3.1

You can also check my other Article on ASP.NET Core Caching: https://procodeguide.com/programming/aspnet-core-caching/

Hope you found this article useful
Buy me a coffeeBuy me a coffee

Leave a Reply

Your email address will not be published. Required fields are marked *