在Angular中,当调用API时,通常会使用Http服务。当API返回错误响应时,Angular会捕获该错误并返回一个错误对象,其中包含该响应的一些信息。
然而,有时候我们希望在错误对象中包含更多的信息,例如API返回的特定错误消息。为了实现这个目标,我们可以通过使用RxJS的“catchError”操作符来转换错误响应。
下面是一个示例,展示了如何在Angular中捕获API错误并将其转换为我们自己的定义错误:
import { Injectable } from '@angular/core'; import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { catchError } from 'rxjs/operators'; import { throwError } from 'rxjs';
@Injectable({ providedIn: 'root' }) export class ApiService {
constructor(private http: HttpClient) { }
getData() {
return this.http.get('https://my.api.com/data')
.pipe(
catchError((error: HttpErrorResponse) => {
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
// A client-side error occurred. Handle it accordingly.
errorMessage = An error occurred: ${error.error.message}
;
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
errorMessage = API returned an error: ${error.status}, ${error.error.message}
;
}
// return an observable with a user-facing error message
return throwError(errorMessage);
})
);
}
}
在本例中,我们'catchError”操作符传递给HTTP请求的管道。在这个操作符中,我们可以定义我们自己的错误处理程序。
在这个例子中,我们首先检查错误是客户端错误还是服务器错误,并相应地生成用户友好的错误消息。然后,我们抛出一个包含错误消息的新错误对象。这个新的错误对象将被作为一个可观察对象返回给调用方。
使用这