Federico Jousset
Federico Jousset

Reputation: 1761

Log D365 script errors on Application Insights

I'm trying to use Application Insights to automatically log form/script errors from my Dynamics 365 instance but they're not being tracked.

I started by creating an Application Insights resource in Azure and adding the following JavaScript (extracted from the Getting Started section from the App Insights Resource) to my CRM form (just like this walkthrough):

var appInsights=window.appInsights||function(config){
function i(config) { t[config] = function () { var i = arguments; t.queue.push(function () { t[config].apply(t, i) }) } }var t={config:config},u=document,e=window,o="script",s="AuthenticatedUserContext",h="start",c="stop",l="Track",a=l+"Event",v=l+"Page",y=u.createElement(o),r,f;y.src=config.url||"https://az416426.vo.msecnd.net/scripts/a/ai.0.js";u.getElementsByTagName(o)[0].parentNode.appendChild(y);try{t.cookie = u.cookie}catch(p){}for(t.queue=[],t.version="1.0",r=["Event","Exception","Metric","PageView","Trace","Dependency"];r.length;)i("track"+r.pop());return i("set"+s),i("clear"+s),i(h+a),i(c+a),i(h+v),i(c+v),i("flush"),config.disableExceptionTracking||(r="onerror",i("_"+r),f=e[r],e[r]=function(config,i,u,e,o){var s=f&&f(config,i,u,e,o);return s!==!0&&t["_"+r](config,i,u,e,o),s}),t
    }({
            instrumentationKey:"XXXXX"
    });

    window.appInsights=appInsights;
    appInsights.trackPageView();

After this, I started to see data related to page views and page load times so the tracking is enabled:

enter image description here

My next action was then to force some script errors in the form to visualize then in Azure. In order to do this, I added a JavaScript function in the OnChange event of a field to get an "undefined" error:

enter image description here

As you can see in the previous image, the error is being thrown in D365 as expected but there's no record of it in Application Insights. After some tests I started to suspect that CRM is catching that error and not letting it to reach the browser (the error doesn't appear in the console). To confirm my suspicions, I created a HTML web page with the same App Insights configuration and I simulated the error to see if in that scenario the errors are being tracked and the answer is yes:

enter image description here

So it seems that Dynamics is "swallowing" the error and preventing it to be logged. Have anyone faced this issue before? Is there a workaround that I can use to successfully track the errors into App Insights?

Thanks!

Upvotes: 1

Views: 756

Answers (1)

Dynamics CRM will handle custom script block in a special way.

We have to catch the exception gracefully in our form js & log it in AppInsights like below.

try
{
   ...
}
catch (ex)
{
   appInsights.trackException(ex);
}

Reference

Upvotes: 1

Related Questions