在app.module.ts中,确保已经导入了ErrorHandler模块,并将它添加到providers中。如下所示:
import { ErrorHandler } from '@angular/core';
export class MyCustomErrorHandler implements ErrorHandler {
handleError(error) {
console.error('An error occurred:', error);
// Do something with the error (e.g. send it to the server)
}
}
@NgModule({
declarations: [...],
imports: [...],
providers: [
{ provide: ErrorHandler, useClass: MyCustomErrorHandler },
],
bootstrap: [...]
})
export class MyAppModule { }
为了确保错误处理器已经被调用,可以在MyCustomErrorHandler中添加console语句或者断点,然后手动抛出一个错误以测试。如下所示:
export class MyCustomErrorHandler implements ErrorHandler {
handleError(error) {
console.error('An error occurred:', error);
// Do something with the error (e.g. send it to the server)
// Test if the error handler is working correctly
throw error;
}
}
如果需要更精细的错误处理,可以调用catch操作符并利用RxJS Observables:
import { Injectable, ErrorHandler } from '@angular/core';
import { Observable, of } from 'rxjs';
@Injectable()
export class MyCustomErrorHandler implements ErrorHandler {
handleError(error: any): Observable {
console.error('An error occurred:', error);
// ToDo: Send the error to the server
// Return an empty observable to prevent the application from crashing
return of(undefined);
}
}
如果在使用RxJS的操作符时遇到错误,可能是由于未引入rxjs/operators。可以在module.ts文件中的imports中添加以下代码:
import { of } from 'rxjs';
import { catchError } from 'rxjs/operators';
@NgModule({
imports: [
...
catchError((err, caught) => {
console.error(err);
throw err