我们需要扩展Angular中的CustomErrorHandler,以处理我们自定义的异常。示例如下:
定义自定义异常类:
export class CustomException extends Error { constructor(public message: string) { super(message); } }
在app.module.ts中配置我们的自定义ExceptionHandler:
import { NgModule, ErrorHandler } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { CustomExceptionHandler } from './custom-exception-handler';
@NgModule({ imports: [ BrowserModule, FormsModule ], declarations: [ AppComponent ], providers: [ { provide: ErrorHandler, useClass: CustomExceptionHandler } ], bootstrap: [ AppComponent ] }) export class AppModule { }
定义CustomExceptionHandler:
import { Injectable, ErrorHandler } from '@angular/core'; import { CustomException } from './custom-exception';
@Injectable() export class CustomExceptionHandler implements ErrorHandler { handleError(error) { if (error instanceof CustomException) { console.error('Custom Exception occurred: ', error); } else { console.error('An unhandled exception occurred: ', error); } } }
现在我们就可以使用我们定义的CustomException类,并确保CustomExceptionHandler能够捕获和处理它所引发的异常。