How to clear the exception to prevent being logged twice by Application Insights

Mykhailo Kostiuchenko 1 Reputation point
2022-10-13T11:39:29.957+00:00

I installed Application Insights into my ASP.NET Web API application. I added global exception handler to log specific exception as a custom events to App Insights:

public class AppExceptionHandler : ExceptionHandler  
{  
    private readonly IAuthEventLogger _authEventLogger;  
  
    public AppExceptionHandler()  
    {  
        _authEventLogger = DependencyResolver.Current.GetService<IAuthEventLogger>();  
    }  
  
    public override void Handle(ExceptionHandlerContext context)  
    {  
        Exception ex = context.Exception;  
        IHttpActionResult newResult = null;  
  
        while (ex != null)  
        {  
            if (ex is AppSessionException)  
            {  
                newResult = new StatusCodeResult(HttpStatusCode.Unauthorized, context.Request);  
                _authEventLogger.TrackUnauthorizedRequestEvent(context.Request.RequestUri.PathAndQuery);  
  
                break;  
            }        
        }  
  
        if (newResult != null)  
        {  
            context.Result = newResult;  
        }  
        else  
        {  
            base.Handle(context);  
        }  
    }  
}  

It works fine, But now all the exceptions are logged twice: in addition to custom events that my logger writes to, exceptions are also logged automatically in the "Failures" App Insights section.

Is there a way to not log automatically my custom exceptions as "Failures" and log all others?

Azure Monitor
Azure Monitor
An Azure service that is used to collect, analyze, and act on telemetry data from Azure and on-premises environments.
3,285 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
338 questions
Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
7,807 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.