当Angular应用程序中发生错误时,给用户显示浏览器的默认错误消息可能不够友好或不够详细。可以通过创建自定义错误处理程序来显示自定义的错误消息。
首先,创建一个名为ErrorInterceptor的类,实现HttpInterceptor接口。在intercept方法中,可以检查HttpErrorResponse,并将错误消息传递给您选择的错误处理服务。
import { Injectable } from '@angular/core';
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { ErrorService } from './error.service';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private errorService: ErrorService) {}
intercept(request: HttpRequest, next: HttpHandler): Observable> {
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
// client-side error
errorMessage = `Error: ${error.error.message}`;
} else {
// server-side error
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
// send the error to the error service
this.errorService.handleError(errorMessage);
// throw the error
return throwError(errorMessage);
})
);
}
}
然后,创建一个名为ErrorService的服务,可以在整个应用程序中共享,并定义一个名为handleError的方法来显示错误消息。
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ErrorService {
private errorSubject = new Subject();
public error$ = this.errorSubject.asObservable();
handleError(errorMessage: string): void {
this.errorSubject.next(errorMessage);
}
}
最后,在你的根模块中(例如app.module.ts)注入ErrorInterceptor,以便在整个应用程序中使用该拦截器。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ErrorInterceptor } from './error.interceptor';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule { }
现在,当发生HTTP错误时,会调用ErrorInterceptor并将错误消息传递给ErrorService。订阅error$可观察对象并显示错误消息的组件可以通过ErrorService访问它。