Building Custom Exception Filters and Logging in Web Api and Mvc

Exception Handling in ASP.NET: Building Custom Exception Filters and Logging

In ASP.NET applications, proper exception handling and error logging are crucial for maintaining the stability and reliability of your web services and applications. This article will guide you through creating a comprehensive exception handling and logging system that spans from defining your database schema to implementing custom exception filters for both ASP.NET Web API and MVC applications. We will also cover how to add these filters to your application’s filter configuration and create an ExceptionLogger class to log exceptions.

Step 1: Define the Database Schema

First, let’s define a database schema for logging exceptions. We will create a table called ExceptionLog to store details about exceptions that occur within your application. Here’s the SQL script for creating this table:

CREATE TABLE ExceptionLog (
    Id INT IDENTITY(1,1) PRIMARY KEY,
    Timestamp DATETIME2 DEFAULT GETDATE(),
    Message NVARCHAR(MAX),
    StackTrace NVARCHAR(MAX)
);

Step 2: Create the Database Model (DbModel)

To interact with the ExceptionLog table, you’ll need a C# model class that represents the table’s structure. Here’s the ExceptionLog model:

using System;
using System.ComponentModel.DataAnnotations;

public class ExceptionLog
{
    [Key]
    public int Id { get; set; }
    public DateTime Timestamp { get; set; }
    public string Message { get; set; }
    public string StackTrace { get; set; }
}

Step 3: Implement DbContext (DbContex)

Now, create a DbContext class to handle database operations for the ExceptionLog model. Make sure to configure your database connection and add a DbSet property for the ExceptionLog model.

using System.Data.Entity;

public class ExceptionLogDbContext : DbContext
{
    public DbSet<ExceptionLog> ExceptionLogs { get; set; }

    // Configure your database connection in the constructor
    public ExceptionLogDbContext() : base("YourConnectionStringName")
    {
    }
}

Step 4: Create Custom Exception Filters

Web API Exception Filter

To create a custom exception filter for ASP.NET Web API, implement the IExceptionFilter interface. The filter will log exceptions and return appropriate error responses.

using System;
using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;

public class ApiExceptionFilter : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        // Log the exception using your ExceptionLogger class.
        ExceptionLogger.LogException(context.Exception);

        // Create an HttpResponseMessage with an appropriate error status code and message.
        var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
        {
            Content = new StringContent("An error occurred."),
            ReasonPhrase = "Internal Server Error"
        };

        context.Response = response;
    }
}

MVC Exception Filter

For ASP.NET MVC, create a custom exception filter by implementing the IExceptionFilter interface. This filter will log exceptions and return appropriate view results.

using System;
using System.Web.Mvc;

public class MvcExceptionFilter : IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        // Log the exception using your ExceptionLogger class.
        ExceptionLogger.LogException(filterContext.Exception);

        // Redirect to an error view or return an appropriate view result.
        filterContext.ExceptionHandled = true; // Mark the exception as handled

        filterContext.Result = new ViewResult
        {
            ViewName = "Error" // Specify the name of your error view
        };
    }
}

Step 5: Add Filters to FilterConfig

Now, add your custom exception filters to the filter configuration for your Web API and MVC applications. In your FilterConfig.cs (for MVC) and WebApiConfig.cs (for Web API), add the filters to the GlobalFilters.Filters collection or the HttpConfiguration.Filters collection.

For MVC (in FilterConfig.cs):

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new MvcExceptionFilter());
        // Other filters...
    }
}

For Web API (in WebApiConfig.cs):

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Filters.Add(new ApiExceptionFilter());
        // Other configuration...
    }
}

Step 6: Create the ExceptionLogger Class

To log exceptions, create an ExceptionLogger class. This class will be responsible for logging exceptions to the database using Entity Framework or any other logging mechanism of your choice.

public class ExceptionLogger
{
    public static void LogException(Exception ex)
    {
        using (var dbContext = new ExceptionLogDbContext())
        {
            var exceptionLog = new ExceptionLog
            {
                Timestamp = DateTime.Now,
                Message = ex.Message,
                StackTrace = ex.StackTrace
            };

            dbContext.ExceptionLogs.Add(exceptionLog);
            dbContext.SaveChanges();
        }
    }
}

Conclusion

By following these steps, you’ve established a robust exception handling and logging system in your ASP.NET application. Exceptions that occur within your Web API and MVC controllers will be caught and logged, helping you diagnose issues and maintain the reliability of your application. Customize the logging and error response logic further based on your specific requirements and preferences.