Search code examples
angularintegrationsentryangular2-webpack-starter

How to integrate Sentry with Angular2-webpack-starter


on Sentry documentation thera are instructions to integrate sentry with Angular2 CLI, but there is a lack of instructions to integrate sentry with Angrular2-webpack-starter. How to do it properly?


Solution

  • I give answer for latest version of angular2-webpack-starter from 8 March 2017 [55d4325]. In this solution, Sentry will be enabled only in production build (normal and AoT) for which it will also throw exceptions in console (but no so 'full featured' exception as are thrown by development builds). Instruction:

    First go to project directory and in console run:

    npm install raven-js --save
    

    Second, create file: ./src/app/app.sentry.ts

    import * as Raven from 'raven-js'; // http://sentry.io
    import { ErrorHandler } from '@angular/core';
    
    // below 'if' is needed to activate sentry ONLY in production mode.  
    // (without this, import statement in environment.ts initialize sentry in dev)
    if ('production' === ENV) 
    {
        Raven // Sentry configuration http://sentry.io
            .config('https://[email protected]/yyyyyy')
            .install(); // where xxx..xxx= your sentry key, yyyy= sentry project id
    }
    
    export class RavenErrorHandler implements ErrorHandler {
      public handleError(err: any): void {
        Raven.captureException(err.originalError);
        console.error(err);     // show err in browser console for production build
      }
    }
    
    export const SENTRY_PROVIDER =  { provide: ErrorHandler, useClass: RavenErrorHandler };
    

    Last step: Edit file ./src/app/environment.ts and add 2 lines of code - a the top line with import file which we created above

    import * as Sentry from './app.sentry';
    ...    
    

    and one line in the upper-middel part of file in if ('production'==ENV) statement:

    ...
    let _decorateModuleRef = <T>(value: T): T => { return value; };
    
    if ('production' === ENV) {
      enableProdMode();
    
      PROVIDERS.push(Sentry.SENTRY_PROVIDER); // !!!-> SENTRY NEW SECOND CODE LINE
    
      // Production
      _decorateModuleRef = (modRef: any) => {
        disableDebugTools();
    
        return modRef;
      };
    
      PROVIDERS = [
        ...PROVIDERS,
        // custom providers in production
      ];
    
    } 
    ...
    

    And that's all :)

    I also post this solution in sentry github but I'm not sure that they include it in sentry documentation.