7
votes

I try to implement a custom error handler in my app following documentation, but don't know how to access the output of original ErrorHandler stack trace. Why I need original? The stack trace printed to console by original ErrorHandler refers to line numbers from typescript .ts files (at least for my app files). The stack trace that is available in a custom ErrorHandler refers to line numbers from javascript .js files.

An example Angular2 app is as follows:

File main.ts

import {bootstrap} from 'angular2/platform/browser';
import {App} from './app';
import {ExceptionHandler, provide} from "angular2/core";
class MyExceptionHandler  {
    call(error, stackTrace = null, reason = null) {
        let msg = ExceptionHandler.exceptionToString(error);
        console.log(msg);
        console.log('Message: ' + error.message);
        console.log('Stack trace: ' + stackTrace);
    }
}
bootstrap(App, [provide(ExceptionHandler, {useClass: MyExceptionHandler})]);
//bootstrap(App, []);

File app.ts

import {Component} from 'angular2/core'
@Component({
  selector: 'my-app',
  providers: [],
  template: `<div><h2>Hello {{name}}</h2></div>`,
  directives: []
})
export class App {
  constructor() {
    this.name = 'Angular2';
    let arr = ['one', 'two'];
    let val = arr[4].id;
  }
}

The last statement of App constructor throws an error as intended. My custom error handler prints a few things to console, but the stack traces only contain line numbers from javascript files.

If you comment the bootstrap which uses custom ExceptionHandler and only execute the original bootstrap and check console, there will be a stack trace with line numbers from TypeScript files. Like below (app.ts:18)

angular2.dev.js:23501 TypeError: Cannot read property 'id' of undefined
    at new App (app.ts:18)

I would like to somehow access this output in my custom handler and send it somewhere else instead of printing to console, but with line numbers from .ts files.

1

1 Answers

0
votes
import {ExceptionHandler, provide} from "angular2/core";

export interface IExceptionHandler {
    call(exception: any, stackTrace?: any, reason?: string): void;
}

export class MyCutomExceptionHandler implements IExceptionHandler {
    call(exception: any, stackTrace: any, reason: string): void {

        alert(exception);
        let msg = ExceptionHandler.exceptionToString(exception);
        console.log("micronyks");
        console.log(msg);
        console.log('Message:---->N ' + exception.message);
        console.log('Stack trace:----->N ' + stackTrace);
    }
}

@Component({
selector: 'my-app', 
  template: `
        main component   
  `,
  directives: [],
})
export class ParentCmp {
    constructor() {
    this.name = 'Angular2';
    let arr = ['one', 'two'];
    let val = arr[4].id;
  }

}

bootstrap(ParentCmp, [provide(ExceptionHandler, {useClass: MyCutomExceptionHandler})]);