Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch Angular 2 exceptions

If Angular 2 encounters an internal exception, it won't be logged to the console.

How can I detect such exceptions like the following one?

EXCEPTION: Error during instantiation of MainFormComponent!.
ORIGINAL EXCEPTION: TypeError: Cannot set property 'crashMeMaybe' of undefined
ORIGINAL STACKTRACE:
... stacktrace ...
ERROR CONTEXT:
... context object ...

Are there any available subscriptions? Where is such documentation?

like image 358
Gábor Imre Avatar asked Feb 10 '23 08:02

Gábor Imre


1 Answers

There is interface ExceptionHandler through which you can provide custom implementation of your choosing. See here and documentation.

From BETA.0 sources: (facade/exception_handler.d.ts)

/**
 * Provides a hook for centralized exception handling.
 *
 * The default implementation of `ExceptionHandler` prints error messages to the `Console`. To
 * intercept error handling,
 * write a custom exception handler that replaces this default as appropriate for your app.
 *
 * ### Example
 *
 * ```javascript
 *
 * class MyExceptionHandler implements ExceptionHandler {
 *   call(error, stackTrace = null, reason = null) {
 *     // do something with the exception
 *   }
 * }
 *
 * bootstrap(MyApp, [provide(ExceptionHandler, {useClass:    MyExceptionHandler})])
 *
 * ```
 */

UPDATED:

I had a little problem with BETA.0

  • the import had to be hacked,
  • the interface seems to be polluted with internal details.

I've run it like:

import {ExceptionHandler} from 'angular2/src/facade/exception_handler';

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

export class CustomExceptionHandler implements IExceptionHandler {
    call(exception: any, stackTrace: any, reason: string): void {
        alert(exception);
    }
}

bootstrap(DemoApp, [
    new Provider(ExceptionHandler, {
        useClass: CustomExceptionHandler
    })
]);
like image 130
wendro Avatar answered Feb 16 '23 12:02

wendro