【问题标题】:Angular6 HttpClient error handling within map地图中的Angular6 HttpClient错误处理
【发布时间】:2019-10-25 00:49:17
【问题描述】:

我在我的服务中使用 angular6 HTTPClient,并希望为订阅者维护 Observable 的 next 和 err 路径。

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

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')
    });
}

我的服务正在使用管道以及地图和 catchError。

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 的方式来做到这一点。

我所期望的是点击错误处理程序的“error.error instanceof ErrorEvent”路径。我不明白“错误:HttpErrorResponse”参数是如何更新的 - 我只是抛出一个“新错误('解析数据失败');”。

有什么建议/建议吗?

【问题讨论】:

    标签: angular error-handling rxjs httpclient


    【解决方案1】:

    根据您的代码,很明显catchError 回调可以采用HttpErrorResponseError 类型。所以catchError回调输入应该是anyError | 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');
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-21
      • 2018-06-26
      • 1970-01-01
      • 1970-01-01
      • 2016-12-20
      • 1970-01-01
      • 2023-03-14
      • 2019-02-01
      • 1970-01-01
      相关资源
      最近更新 更多