在使用 Angular 8 开发 Web 应用时,我们经常会使用 HTTP 请求来获取数据或发送数据。但是,由于网络环境不稳定,HTTP 请求也可能出现错误。在这种情况下,我们需要捕获这些 HTTP 请求错误,并对它们进行全局错误处理。
下面将介绍如何在 Angular 8 中实现全局错误处理。本教程包含以下内容:
- 如何在 Angular 8 中捕获 HTTP 请求错误
- 如何在应用程序中实现全局错误处理
- 如何处理特定的 HTTP 请求错误
- 示例代码
如何在 Angular 8 中捕获 HTTP 请求错误
在 Angular 8 中,我们可以使用拦截器(interceptor)来捕获 HTTP 请求错误。拦截器是 Angular 中的一个特殊服务,它可以检查和修改 HTTP 请求和响应。我们可以使用拦截器来捕获 HTTP 请求错误,并在控制台或 UI 中显示错误信息。
以下是如何创建一个 HTTP 请求拦截器的步骤:
- 创建一个名为
HttpErrorInterceptor的 TypeScript 类。 - 在该类中实现
HttpInterceptor接口。 - 在该类中实现
intercept()方法,该方法接收原始的 HTTP 请求对象和next参数。 - 在
intercept()方法中用pipe()运算符调用原始的handle()方法。 - 在
pipe()运算符中使用catchError()运算符捕获 HTTP 请求错误,并将它们重新抛出。
以下是一个示例 HttpErrorInterceptor 类:
// www.javascriptcn.com code example
import { Injectable } from '@angular/core';
import {
HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
constructor() { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
console.error(error);
return throwError(error);
})
)
}
}如何在应用程序中实现全局错误处理
在应用程序中实现全局错误处理的方法与上一步类似。我们只需在应用程序的根组件中提供 HttpErrorInterceptor 类,就可以在整个应用程序中捕获 HTTP 请求错误。以下是如何实现全局错误处理的步骤:
- 打开
app.module.ts文件。 - 导入
HTTP_INTERCEPTORS常量。 - 导入
HttpErrorInterceptor类。 - 编写
providers属性以提供HttpErrorInterceptor类。
以下是一个示例应用程序的 app.module.ts 文件:
// www.javascriptcn.com code example
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpErrorInterceptor } from './http-error.interceptor';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
AppRoutingModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: HttpErrorInterceptor,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }如何处理特定的 HTTP 请求错误
有时,我们不想在全局错误处理程序中处理特定的 HTTP 请求错误。例如,我们可能需要为不同类型的 HTTP 请求错误显示不同的错误消息。
以下是如何处理特定的 HTTP 请求错误的步骤:
- 在拦截器中检查错误的类型,例如 404 或 500。
- 为特定类型的错误返回自定义错误消息。
- 创建一个新的
HttpErrorResponse对象,以便提供自定义错误消息。 - 将新的
HttpErrorResponse对象传递给throwError()函数。
以下是一个示例 HttpErrorInterceptor 类,它为特定类型的 HTTP 请求错误提供了自定义错误消息:
// www.javascriptcn.com code example
import { Injectable } from '@angular/core';
import {
HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
constructor() { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
// 客户端错误
errorMessage = `客户端错误:${error.error.message}`;
} else {
// 服务器错误
switch (error.status) {
case 404:
errorMessage = '请求的页面不存在';
break;
case 500:
errorMessage = '服务器错误,请稍后再试';
break;
default:
errorMessage = `出现了一个未知错误:${error.message}`;
break;
}
}
console.error(errorMessage);
return throwError(new HttpErrorResponse({
error: errorMessage,
status: error.status,
statusText: error.statusText,
url: error.url
}));
})
)
}
}示例代码
以下是一个示例应用程序,它使用 HttpClient 从远程 API 获取数据,并捕获和处理 HTTP 请求错误。
// www.javascriptcn.com code example
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
interface Post {
userId: number;
id: number;
title: string;
body: string;
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
posts: Post[];
errorMessage: string;
constructor(private http: HttpClient) { }
ngOnInit() {
this.http.get<Post[]>('https://jsonplaceholder.typicode.com/posts').subscribe(
result => {
this.posts = result;
},
error => {
this.errorMessage = error.error;
}
);
}
}在上面的示例中,AppComponent 类在初始化时使用 HttpClient 从远程 API 获取数据。如果发生 HTTP 请求错误,它会捕获该错误,并将错误消息存储在 errorMessage 变量中。 AppComponent 类的 HTML 模板会根据是否出现错误显示不同的界面。
如果出现 HTTP 错误,我们可以在 UI 中显示错误消息,让用户知道出现了什么问题。
在这篇文章中,我们讨论了如何在 Angular 8 中捕获和处理 HTTP 请求错误。全局错误处理使我们能够在任何地方处理错误,而不必为每个 HTTP 请求单独编写错误处理代码。这有助于简化我们的代码,并提高应用程序的可维护性。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d64519a941bf7134bf7efd