ClearInsights .NET Global Exception Handling

Global exception handling enables an application with a much broader ability to handle all exceptions. This is usually done through custom middleware for ASP.NET core applications or AppDomain unhandled exception event for .NET core console and service applications. ClearInsights logging simplifies the implementation and management of global exception handling while reducing the time in which a bug is found and fixed. This is achieved by automatically pushing newly discovered bugs to your team’s backlog.

Below are some examples of how to implement ClearInsights global exception handling into your applications.

ASP.NET Core

using ClearInsights.Logging;
using System.Net;

var builder = WebApplication.CreateBuilder(args);

//Add to capture logs with ClearInsights Logging
builder.Logging.AddClearInsightsLogger(configuration =>
{
    configuration.ApiKey = "{ApiKey}";
    configuration.Secret = "{Environment Client Secret}";
    configuration.ApplicationName = "{Application Name}";
});


var app = builder.Build();

//Add to use ClearInsights global error handling.
//This will automatically catch and log any unhandled exceptions
app.UseClearInsightsExceptionHandling(options =>
{
    //Add to extend the error handler and add additional logic.
    //Add logic like custom HTTP response, etc...
    options.OnError += (sender, arg) =>
    {
        var response = "Oops something went wrong";
        arg.HttpContext.Response.ContentType = "text/html";
        arg.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
        arg.HttpContext.Response.WriteAsync(response);
    };
});

.NET Core

using ClearInsights.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

using IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureLogging(builder =>
        builder.ClearProviders()
            //Add to capture logs with ClearInsights Logging
            .AddClearInsightsLogger(configuration =>
            {
                configuration.ApiKey = "{ApiKey}";
                configuration.Secret = "{Environment Client Secret}";
                configuration.ApplicationName = "{Application Name}";
            }))    
            .Build();

//Add to use ClearInsights global error handling.
//This will automatically catch and log any unhandled exceptions
System.AppDomain.CurrentDomain.UseClearInsightsExceptionHandling(host.Services.GetRequiredService<ILogger<Program>>());

An Expert Guide to Effective Log Management

Competitive fast-paced markets more and more require applications that are solution driven, scalable and user friendly.

Accomplishing these goals often require an effective log management strategy to provide better clarity performance.

Learn about:

  • Centralized Log Management
  • Defect Management
  • Logging Best Practices

Leave a Reply