ExceptionFilterAttribute may not be logging exceptions in ApplicationInsights - asp.net-core

Do exceptions that are filtered with a custom ExceptionFilterAttribute logged to Application Insights?
I want to return a custom DTO in my custom ExceptionFilterAttribute filter, but I think exceptions are no longer logged into ApplicationInsights after that. This is for .NET Core 3.0.
I added a line with:
this.telemetryClient.TrackException(context.Exception);
to make sure I can see the exception but I'm not sure if my exceptions are logged twice now.
Does anyone know if ApplicationInsights will log exception if they enter ExceptionFilterAttribute? I can't find documentation for this.
I'm calling just in case also:
base.OnException(context);

Does anyone know if ApplicationInsights will log exception if they
enter ExceptionFilterAttribute?
Yes, it will log the exceptions, so you do not need to add this line of code this.telemetryClient.TrackException(context.Exception);. Just using base.OnException(context); is ok.
You can see this GitHub issue for the similar issue, the reason is that "With new Ilogger enablement by default, exceptions are automatically reported by application insights.".
I also check it via a simple test, the test result as below:

Related

CefSharp.BrowserSubProcess.Core WCF pipe failure

Our application is using CefSharp version 73.1.130. The issue only occurs on a small number of internal workstations within our organization. Worth noting, we are also seeing the same error with CefSharp version 92. Another strange thing is that it the issue is consistent, but only when the web apps are launched through certain navigations. Other navigations work consistently for these users.
We use RegisterJsObject to register a javascript object with browser. If I understand correctly, asynchronous binding is preferred moving forward.
The issue presents as strange/unexpected behavior in the hosted web application due to failure to retrieve context from the host WinForms application. The behavior would suggest a failure to register/bind the js object with the RegisterJsObject method. However, that method is not throwing an exception.
Enabled Cef logging showed the following error:
ERROR:JavascriptRootObjectWrapper.cpp(34)] IBrowserProcess is null, unable to bind object
After looking into the code, it appears the location that the value pointed to by "IBrowserProcess" is set is in WcfEnabledSubProcess::OnBrowserCreated (https://github.com/cefsharp/CefSharp/blob/cefsharp/73/CefSharp.BrowserSubprocess.Core/WcfEnabledSubProcess.cpp). I was able to build CefSharp and add additional logging to that method.
On my workstation (I'm not affected by the issue), I get through OnBrowserCreated with no exceptions. However, on my coworkers workstation I see the following line is failing:
...
channelFactory->Open();
auto browserProcess = channelFactory->CreateChannel();
auto clientChannel = ((IClientChannel^)browserProcess);
try
{
clientChannel->Open(); <-- FAILS
browser->ChannelFactory = channelFactory;
browser->BrowserProcess = browserProcess;
}
catch (Exception^)
{
}
}
With the error:
There was an error reading from the pipe: The pipe has been ended. (109, 0x6d)
Has anyone seen this issue before? I'm not sure how much this will help, but does anyone know if it's possible to enable WCF tracing with the CefSharp.BrowserSubProcess.exe. I have been trying this, but no luck so far.

Error in 3rd Party Library Causing Hanging in Release

My main program is an ASP.Net Core Web API that has a third party library in a hosted service. The third party library is initializing fine but then it throws some errors sometime throughout its lifecycle.
It supplies a way of hooking into the object via an event and will let me know what the error is so that I can handle it but it still throws in the third party library..
Since I am handling the event myself, I want to completely ignore these errors that are occurring in this library. Is there anyway that I can do that?
I have already tried to add a global exception handler and the strange thing is, this exception handler never gets hit. The only way I can get the exception is to set my exception settings to break when CLR exceptions happen like in the picture above
This does not crash my program. For some reason, the program just hangs. When I turn off CLR exceptions in the "Break when thrown" window, then the program runs just fine. It is almost like visual studio is doing something special to handle these types of exceptions that a console version cannot do
The only way that I can seem to get a console version of this running, is attach a visual studio debugger to the process and when the exception is hit, press the green play button "Continue" in visual studio. Otherwise the application just seems to hang on the exception being thrown by the third party library.
The application will run fine as long as visual studio is attached and the CLR break exceptions are not checked
Does anyone know how to make sure that these types of exceptions do not hang the program when released?
Additional Info:
The third party library is a .NET Framework 4 library
The Asp.Net project is targetting "net5.0-windows"
The 3rd party class is probably using multi-threading
if it helps, this is how I am creating the third party class
Handling NullReferenceException in release code(Official advice)
It's usually better to avoid a NullReferenceException than to handle it after it occurs. Handling an exception can make your code harder to maintain and understand, and can sometimes introduce other bugs. A NullReferenceException is often a non-recoverable error. In these cases, letting the exception stop the app might be the best alternative.
However, there are many situations where handling the error can be useful:
1.Your app can ignore objects that are null. For example, if your app retrieves and processes records in a database, you might be able to ignore some number of bad records that result in null objects. Recording the bad data in a log file or in the application UI might be all you have to do.
2.You can recover from the exception. For example, a call to a web service that returns a reference type might return null if the connection is lost or the connection times out. You can attempt to reestablish the connection and try the call again.
3.You can restore the state of your app to a valid state. For example, you might be performing a multi-step task that requires you to save information to a data store before you call a method that throws a NullReferenceException. If the uninitialized object would corrupt the data record, you can remove the previous data before you close the app.
4.You want to report the exception. For example, if the error was caused by a mistake from the user of your app, you can generate a message to help them supply the correct information. You can also log information about the error to help you fix the problem. Some frameworks, like ASP.NET, have a high-level exception handler that captures all errors to that the app never crashes; in that case, logging the exception might be the only way you can know that it occurs.
So after days of research I've finally found an event to hook into to give you error messages from ANY source no matter how many level deep you go in threads.
AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;
Hooking into this event it will allow you to see errors from every library and every thread. Simply place the above into you program.cs (or whatever startup file you have) and magically you will be flooded with all of the unknown errors from all of the 3rd party libraries you thought were once flawless.
private static void CurrentDomain_FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
{
Console.WriteLine(e.Exception.Message, e.Exception.StackTrace);
}
I've done so with the following method and low and behold. The third party library was trying to reference another project in an unsafe way and throwing an error. Since I didn't need this other project reference the built exe did not have a reference to this assembly because I had no direct reference to it in the project (darn smarty pants who need to optimize everything). I was able to run correctly because in my visual studio solution, I had a reference to this other project. So the third party library would pick up on it as soon as visual studio connected with the debugger through some sort of dark magic.
Anyways, I made a throw away object that used the project that was required and the issue was solved.
I really hope that this helps someone else and saves them the days it took me to find this.

How to prevent MVC5 setting the fTrySkipCustomErrors flag to true automatically

Short Version
Please read at the very bottom for a short version of the question.
Situation
In a question I asked last week, I struggled in finding a solution, which makes our asp.net error visualization waterproof, since there are some edge cases where the asp.net exception handling fails and hence no proper exception visualizations can be created:
How to properly set up ASP.NET web.config to show application specific, safe and user friendly asp.net error messages in edge cases
Desired Solution
As an alternative to the way I described there, in my opinion the best way to make the exception visualization reliable, would be to use the httpErrors-element in system.webServer as a failsave so that any error which is not properly handled by asp.net, leads to a generic error page which is shown based on the settings of the httpErrors-element .
To accomplish this, there must be two things possible:
Error pages properly handled by the application must pass through iis without being replaced with a generic error message
Errors which could not be processed properly in asp.net, must be replaced through IIS.
It is my understanding, that this very behaviour is meant by the existingResponse="Auto" parameter in the httpErrors-element.
The ms documentation states:
Leaves the response untouched only if the SetStatus flag is set.
This is exactly what is necessary: Any successful error page creation in the application (through Application_Error or through an explicitly defined error handling page) can set
Response.TrySkipIisCustomErrors = true and IIS would let the error page pass through. However, every other error which was not successfully handled by the application in asp.net, would not set the flag and hence get the error page which is specified in the httpErrors-element.
The Problem
Sadly, it seems that in MVC5-applications (I don’t known whether the same behavior is true in other environments), the Response.TrySkipIisCustomErrors (fTrySkipCustomErrors) seems to be set automatically to [true], even if it is not set by the application.
Hence we are at the same place, as in my other post: If the error handling of the application blows, there is no way to show an application specific error with existingResponse="Auto", since its not possible to reset the fTrySkipCustomErrors flag.
As an alternative, one can set existingResponse="PassThrough". That's what we do currently, since we want to generate our error pages with a support-code and other helpfull information about the error to be shown to the user, or one can use existingResponse="Replace", but this is not an option, since it replaces any error page so that we don’t can show the user any error-specific information such as the support-code mentionen before.
Quesition in Short
The question is therefore, how to make sure that MVC5 (asp.net) does not set the fTrySkipCustomErrors flag automatically to [true], since there are situations, where no application code is executed and hence the Response.TrySkipIisCustomErrors (fTrySkipCustomErrors) cannot be set to false, what renders the existingResponse="Auto" parameter moot.
To check such a situation where the asp.net MVC5 exception handling blows but the fTrySkipCustomErrors flag is set to true, please request the following page from your MVC5 application:
http[s]://[yourWebsite]/com1
Please note: I'm not interested in disabling the above error. It's an example. I want the error visualization reliable and not to have to circumvent every error that possibly can blow asp.net's error handling mechanisms.

ASP.Net Core - Application Insights - Stack Trace

I'm setting up a pretty simple ASP.Net Core (2.2) MVC Web App. I want to be able to see any application errors (500s) and what caused them so it seems like Application Insights is the place to look.
If I go into Application Insights / Failures (Operations Tab - see screenshot below), I'm able to see a graph/count of all the 500 errors. I can click on "DRILL INTO" button and see a lof of the details (Event Time, Request Name, etc...) but cannot seem to get any details on the actual cause of the error / line number.
Basically, I have the exact same problem as this person:
Azure Monitor / Application Insights not showing stack trace for errors
(my screenshots look identical).
When I drill down to the exception details, I get something like this:
I'm want to get something like this:
I did see info on adding Application Insights via Nuget to my solution and putting
services.AddApplicationInsightsTelemetry();
into the Startup/ConfigureServices method.
I also see that you can look at Kudu logs, etc... but I really want this all to be easily accessible in Application Insights.
Any suggestions?
OK - I think I solved my own problem. Turns out I had added Serilog a while back (sort of forgot about that) and it was capturing all the errors before getting to AI. When I removed the Serilog configuration code from Program.cs and Startup.cs, the application exceptions started showing up in Application Insights / Failures along with the full Call Stack. Thanks for your suggestions!
A 500 Internal server error suggests you are looking for the stack trace to identify what went wrong and where. No code has been provided in your example but you will need to surround your code with a try catch and then log the exception to get the stack trace or you can use the TelemetryClient as below:
var telemetry = new TelemetryClient();
...
try
{ ...
}
catch (Exception ex)
{
// Set up some properties:
var properties = new Dictionary <string, string>
{{"Game", currentGame.Name}};
var measurements = new Dictionary <string, double>
{{"Users", currentGame.Users.Count}};
// Send the exception telemetry:
telemetry.TrackException(ex, properties, measurements);
}
Further information can be found at Microsoft

Catching SQL Exceptions in vb.net

Is there a way to catch all SQL exceptions in a project? I have several gridviews and multiple sqldatasources and most of the errors are going to occur when a user enters something incorrectly or in the wrong column. So how do I stop the Server Error in /Project page from showing up?
The simple answer is, validate the input before you send it to SQL Server. That way, there won't be any exceptions thrown.
If you wish to handle all your errors centrally (which is not the ideal solution for this particular problem), you can set up custom error handling in your web.config file.
I would suggest catching error in the Application_Error event inside your Global.asax in your web application.
The easiest way to catch all exceptions is to do it in Application_error event handler in global.asax, and utilize the web.config custom error handling to show a friendly error page. These are already mentioned by mikeware.
If you want to put all your validation logic in one place / separate them from your aspx pages, you could do it by making your website multi-layered and put your custom validation logic in the middle layer. By using this method, your data will get validated in that layer no matter which page is accessing your data. You can also use objectdatasource to do select/insert/update/delete operation. Obviously it requires some work, but it can clearly separate your data and your UI.