Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unhandled browser exceptions not being tracked in Angular app #71

Closed
chinaowl opened this issue Aug 22, 2017 · 16 comments
Closed

Unhandled browser exceptions not being tracked in Angular app #71

chinaowl opened this issue Aug 22, 2017 · 16 comments

Comments

@chinaowl
Copy link

chinaowl commented Aug 22, 2017

Hello,

I am experiencing this issue that was closed/fixed awhile ago: microsoft/ApplicationInsights-JS#282

I created a brand new Angular app using the Angular CLI. Then I made these changes, following this article.

Added a monitoring service:

import {Injectable} from '@angular/core';

import {AppInsights} from 'applicationinsights-js';

@Injectable()
export class MonitoringService {
  private config: Microsoft.ApplicationInsights.IConfig = {
    instrumentationKey: 'KEY_GOES_HERE',
    enableDebug: true,
    verboseLogging: true
  };

  constructor() {
    if (!AppInsights.config) {
      AppInsights.downloadAndSetup(this.config);
    }
  }

  logPageView(name?: string, url?: string, properties?: any, measurements?: any, duration?: number) {
    AppInsights.trackPageView(name, url, properties, measurements, duration);
  }

  logEvent(name: string, properties?: any, measurements?: any) {
    AppInsights.trackEvent(name, properties, measurements);
  }

  trackException(exception: Error) {
    AppInsights.trackException(exception);
  }
}

Added it to my app.component.ts:

import { Component, OnInit } from '@angular/core';
import {MonitoringService} from './monitoring.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [MonitoringService]
})
export class AppComponent implements OnInit {
  title = 'app works!';
  constructor(private monitoringService: MonitoringService) { }

  ngOnInit() {
      this.monitoringService.logPageView();
  }

  throwAnException() {
      this.monitoringService.trackException(new Error('manually track exception'));
      throw 'this should appear in app insights'; // but it doesn't
  }
}

Made a simple button for throwing the exception in my app.component.html:

<h1>
  {{title}}
</h1>
<div (click)="throwAnException()">Click to throw an exception</div>

Logging a page view works, as does tracking the exception by calling trackException. However, I thought all uncaught exceptions would get sent to Application Insights automatically, but I am not seeing any of those show up in the portal. Am I missing something else?

I am using these versions:

applicationinsights-js: 1.0.11
@types/applicationinsights-js: 1.0.4
@dmf07
Copy link

dmf07 commented Nov 13, 2017

Angular handles all the uncaught exceptions. Try implementing an https://angular.io/api/core/ErrorHandler and call trackException from there.

@ifflanb
Copy link

ifflanb commented Nov 21, 2017

Hi I am experiencing the same issue but in my ReactJS application.
I have added the following script to each page of our site (guess that is just one page as its a SPA)

`<script type="text/javascript">
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,s}),t
}({
instrumentationKey:"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
enableDebug: true,
verboseLogging: true
});

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

</script>`

Then if I try to throw an exception e.g. throw new Error(), the error is not logged to App Insights. I can get errors appearing if I manually track them with the AppInsights.trackException syntax.

@KamilSzostak KamilSzostak added the bug Something isn't working label Jan 16, 2018
@NateWarner
Copy link

NateWarner commented Feb 23, 2018

This issue is affecting us as well. It is also not relegated to Angular as it affects all unhandled exception errors.

In the meantime we're going to listen to window.onerror and log the exception manually so we have some insight into unhandled exceptions occurring. Doing this means we'll likely be doubling up on our error logging once this issue is fixed.

@QuentinLuc
Copy link

Hello @KamilSzostak , this issue is opened since the 23rd of August. Do you plan to fix it soon?

@gauravhub
Copy link

@KamilSzostak, we are also impacted by this issue. Appreciate if you can give some info regarding ETA for a fix related to this.

@jean-moldovan
Copy link

As it was mentioned before, looks like exceptions are caught by the framework. In order to pass them over to app insights you need have a global error handler and call trackException from there.

Using Vue as an example (similar should apply to React and Angular):

    Vue.config.errorHandler = (err, vm) => {
      AppInsights.trackException(err)
      console.error(err)
    }

This is how error reporting tools like Sentry work. https://github.com/bugsnag/bugsnag-vue/blob/master/src/index.js

Curious to know if future appinsights-js v2 will provide Vue, React, Angular adapters out of the box.

Thanks everybody!

@markwolff
Copy link

There are existing app insights libraries which are built on top of this one that integrate well with the various frontend frameworks, e.g. React and Vue. They are only community supported at this point, so updates may be intermittent and you would need to use their initialization/API surface.

However, some work is being done to make the react-appinsights a plugin/adapter for appinsights v2, to give similar behavior to Sentry (same can eventually be done for Vue, Angular).

@3xj
Copy link

3xj commented Jul 18, 2019

Hi,

I believe I am seeing the same issue. I'm using ai-web 2.1.0 in a pure JS application (no frameworks). When I throw an uncaught exception, I am not seeing it in the exceptions table in Application Insights. I have the same issue with the dependencies table as well, it's logging browser calls etc. but not the fetch call I'm making in my code.

Is it possible that autocollection is off? Is there any way to verify this one way or the other?

@markwolff
Copy link

@3xj Can you switch you maxBatchInterval to 0 and see if it is sending any telemetry for your exceptions. Alternatively, you could have something in your app which is swallowing unhandled exceptions, preventing it from reaching window.onerror

@3xj
Copy link

3xj commented Jul 19, 2019

@markwolff Thanks for the quick response. You were correct, my exceptions were not making it to window.onerror -- I added some code to pass unhandled rejections to it and they started showing up in AI, regardless of what value I have for maxBatchInterval.

I am still not seeing my fetch calls in the dependencies table however, which I believe I should be? Does that also rely on a global listener somewhere?

@markwolff
Copy link

We patch on top of fetch and XMLHttpRequest, and so if something else in your app is overwriting those instead of patching over it, then you will probably lose our patching there as well. Also, fetch tracking is off by default, so you will need to enable that in your app

@3xj
Copy link

3xj commented Jul 23, 2019

@markwolff Doh -- I missed that fetch tracking was off by default. I've enabled it and am now seeing my calls in the logs. Thanks for your help.

@idanga
Copy link

idanga commented Jan 19, 2020

I added some code to pass unhandled rejections

@3xj what code was that?

@3xj
Copy link

3xj commented Jan 24, 2020

@idanga

window.addEventListener('unhandledrejection', (event) => {
let message;
let error;
try {
message = event.reason.error.message;
error = event.reason.error;
} catch (err) {
message = JSON.stringify(event);
error = err;
}
window.onerror.apply(this, [message, '', null, null, error]);
});

@MSNev
Copy link
Contributor

MSNev commented Jan 24, 2020

We have also added this as an option (thanks to @aaronpowell) in the next release which will be shortly v2.4, we also published this earlier in the month as 2.4-beta to NPM (Not the cdn). Its off by default, but you can enabled by passing enableUnhandledPromiseRejectionTracking = true in the config.

@MSNev MSNev removed the bug Something isn't working label Aug 2, 2022
@MSNev MSNev transferred this issue from microsoft/ApplicationInsights-JS Aug 2, 2022
@github-actions
Copy link

This Issue will be closed in 30 days. Please remove the "Stale" label or comment to avoid closure with no action.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests