How to apply Angular ErrorHandler accross modules

前端 未结 2 2036
隐瞒了意图╮
隐瞒了意图╮ 2021-01-16 19:55

Here\'s my Angular 4 app module:

@NgModule({
declarations: [
    AppComponent
],
providers: [
    QuickBoardListService,
    {provide: ErrorHandler, useClass         


        
2条回答
  •  佛祖请我去吃肉
    2021-01-16 20:23

    First, let's define a GlobalErrorHandler class that will inherit from ErrorHandler like so:

    import { ErrorHandler, Injectable, Injector } from '@angular/core';
    import { LoggingService } from '../services';  //<-- Replace this with your logging service or something similar
    
    @Injectable()
    export class GlobalErrorHandler implements ErrorHandler {
    
    constructor(private injector: Injector) { }
    
    handleError(error) {
        const loggingService = this.injector.get(LoggingService);
        const message = error.message ? error.message : error.toString();
          // log on the server
          loggingService.log({ message });
        });
        throw error;
      }
    
    }
    

    Now you have to tell Angular to use your GlobalErrorHandler instead of the default one adding the provider to your app.module.ts:

    import { NgModule, ApplicationRef, ErrorHandler } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    
    import { GlobalErrorHandler } from './error-handler'; //<-- adapt the "from" to your file
    import { ServicesModule } from './services';
    
    import { AppComponent } from './app.component';
    
    @NgModule({
      declarations: [AppComponent],
      imports: [BrowserModule],
      bootstrap: [AppComponent],
      providers: [
        {
          provide: ErrorHandler, 
          useClass: GlobalErrorHandler
        }
      ]
    })
    export class AppModule { }
    

提交回复
热议问题