angular - 映射中的Angular6 HttpClient错误处理

标签 angular error-handling rxjs httpclient

我在服务中使用angular6 HTTPClient,并希望维护Observable到订阅服务器的下一条路径和错误路径。

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

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

我的服务正在使用管道以及 map 和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”参数-我只是抛出了“新错误('解析数据失败');”。

有什么建议/建议吗?

最佳答案

根据您的代码,很明显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');
}

关于angular - 映射中的Angular6 HttpClient错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56529441/

相关文章:

RxJS 随着时间的推移发出数组项?

angular - RxJs:在 subscribe() 中使用 try/catch 是否正确?

css - Angular2 最终版本不再支持 :host::shadow

python - 如何处理来自谷歌地图 api 的错误?

swift - 在 Swift 中将可选绑定(bind)转换为错误处理的过程是怎样的?

error-handling - 区分 `on error goto`发生的两个错误并分别处理

javascript - 使用 switchmap 和 forkjoin 链接 observables 不能按预期工作 angular typescript rxjs

angular - 加载动态响应表单,不等待http调用完成

angular - 获取全局样式的问题包括在 Nx 和 Angular 12 的故事书中

angular - 从 3.1 升级后.NET Core 5.0 Azure 部署 CORS 问题