【发布时间】:2019-02-07 15:41:35
【问题描述】:
在浏览Angular tutorial 并将其转换为我的目的时,我决定将显示的两种错误处理方法合并为一个,因为我喜欢两者的功能。
这是一站式服务,这是教程中的两种方法:
private handleError1(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.error('An error occurred', error.error.message);
} else {
console.error(`Backend error code ${error.status}`,
`body: ${error.error}`);
}
return throwError('Something bad happened');
}
这样调用,其中Group 是我来自 REST 服务器的类:
getGroups(): Observable<Group[]> {
return this.httpClient.get<Group[]>(`${this.restUrl}/group`).pipe(
tap(_ => this.log(`fetched groups`)),
catchError(this.handleError1)
);
}
然后,还有:
private handleError2<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
console.error(`${operation} failed!`, error);
return of(result as T);
}
}
这样称呼:
getGroups(): Observable<Group[]> {
return this.httpClient.get<Group[]>(`${this.restUrl}/group`).pipe(
tap(_ => this.log(`fetched groups`)),
catchError(this.handleError2<Group[]>('getGroups', []))
);
}
所以我天真地把我的组合错误处理程序放在一起:
private handleError<T>(error: HttpErrorResponse,
operation = 'operation', result?: T) {
....
但我遇到了问题,因为我不知道如何在 catchError() 中对其进行参数化。 HttpErrorResponse 当它是唯一的参数时,显然以某种方式隐含了它,但是如何呢?
【问题讨论】:
标签: angular typescript error-handling rxjs