Asad Naeem
Asad Naeem

Reputation: 636

Implementing ErrorHandler class in Angular 8+ gives the exception at run time

this snippet is from app.module.ts. I just created an angular 9 application 
and tried to implement ErrorHandler class to catch error but it is showing
the error at run time and page does not load.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ErrorHandler } from '@angular/core';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [
    {provide: ErrorHandler, useClass: MyErrorHandler}
  ],
  bootstrap: [AppComponent]
})

class MyErrorHandler implements ErrorHandler {
  handleError(error) {
    alert(error);
    // do something with the exception
  }
}
export class AppModule { }

Exception in browser:

ASSERTION ERROR: Type passed in is not NgModuleType, it does not have 'ɵmod' property.
    at throwError (core.js:1344)
    at assertNgModuleType (core.js:2951)
    at compileNgModuleFactory__POST_R3__ (core.js:42275)
    at PlatformRef.bootstrapModule (core.js:42663)
    at Module../src/main.ts (main.ts:11)
    at __webpack_require__ (bootstrap:79)
    at Object.0 (main.ts:12)
    at __webpack_require__ (bootstrap:79)
    at checkDeferredModules (bootstrap:45)
    at Array.webpackJsonpCallback [as push] (bootstrap:32)

Upvotes: 0

Views: 397

Answers (1)

Yuriy Kravets
Yuriy Kravets

Reputation: 1263

move your MyErrorHandler class to a separate file and import it in your AppModule and it should work.
Angular uses typescript decorators, which are defined above each class they belong to. In your case you were adding a decorator @NgModule to a class MyErrorHandler, that way Angular could not find proper configuration for main AppModule, and that's why you receive such error when compiling.

Upvotes: 1

Related Questions