Angular6 map中的HttpClient错误处理



我在我的服务中使用了angular6 HTTPClient,并希望维护对订阅者的可观察路径的下一个错误路径。

例如,我的组件看起来像这样:

private myFun(query: string) {
    this.myService.login(data).subscribe(next => {
        // Do successful stuff
        console.log('Got the data: ' + next);
    },
    err => {
       // Handle all errors here
       console.error('good luck next time')
    });
}

我的服务正在使用管道以及地图和捕获错误。

private findData(in: string): Observable<string> {
    return this.http.post<string>(self.url, '')
        .pipe(
            map( response => {
            //Check the data is valid
            if (this.dataValid(response)){
                     return this.convertedData(response);
            } else {
                throw new Error('failed parsing data');
            }
            }),
            catchError(this.handleError)
        );
  }

我可以检测到解析问题并通过catchError引发错误,但我正在努力理解如何处理catchError。

错误处理程序如下所示:

private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
        // Client Side Error
        console.error('Client side error:', error.error.message);
    } else if (error.message === 'failed parsing data') {
        // Client Side Processing Error
        console.error(error.message);
        return throwError(error.message);
    } else {
        // Service Side Error
        console.error(`Server returned code ${error.status}, ` + `body was: ${error.error}`);
    }
    // return an observable error message
    return throwError('failed to contact server');
}

它完成了这项工作,但我忍不住想,必须有一种更好、更 Angular/RxJS 的方式来做到这一点。

我所期望的是命中错误处理程序的"错误事件的错误.错误实例"路径。我不明白"错误:HttpErrorResponse"参数是如何更新的 - 我只是抛出一个"新错误('解析数据失败'(;"。

有什么意见/建议吗?

根据您的代码,很明显catchError回调可以采用HttpErrorResponseError类型。所以catchError回调输入应该像这样any类型或像这样Error | HttpErrorResponse -

private handleError(error: any // or it can be Error | HttpErrorResponse) {
    //now do console.log(error) and see what it logs
    //as per the output adjust your code
    if (error instanceof Error) {
        // Client Side Error
        console.error('Client side error:', error.error.message);
    } else if (error.message === 'failed parsing data') {
        // Client Side Processing Error
        console.error(error.message);
        return throwError(error.message);
    } else {
        // Service Side Error
        console.error(`Server returned code ${error.status}, ` + `body was: ${error.error}`);
    }
    // return an observable error message
    return throwError('failed to contact server');
}

最新更新