【问题标题】:How to catch error in RxJS 5.5如何在 RxJS 5.5 中捕获错误
【发布时间】:2017-11-28 17:58:07
【问题描述】:

我正在使用Angular 5 和 RXJS 5.5

在我能做这样的事情之前

getProjectInfo(id): Observable<any> {
    const URL = `${this.API}/${id}`;
    return this.http.get(URL)
      .pipe(map(res => res)),
      catchError(this.handleServerError);
}

handleServerError(error: any) {
    console.log(error.error || error.json() || error);
    return Observable.throw(error.error || error.json() || error || 'Server error');
}

但现在我得到了这个错误

Error:(21, 5) TS2322:Type 'UnaryFunction<Observable<{}>, Observable<any>>' is not assignable to type 'Observable<any>'.
  Property '_isScalar' is missing in type 'UnaryFunction<Observable<{}>, Observable<any>>'.

我也试过了

getProjectInfo(id): Observable<any> {
    const URL = `${this.API}/${id}`;
    return this.http.get(URL)
      .pipe(map(res => res)),
      catchError(err => this.handleError('getProjInfo', URL));
}
private handleError(method: String, URL: string): any {
  return (err: any) => {
    const errMsg = `error in ${method}() retrieving ${URL}`;
    console.log(`${errMsg}:`, err);
    if (err instanceof HttpErrorResponse) {
      console.log(`status: ${err.status}, ${err.statusText}`);
    }
    return Observable.throw(errMsg);
  };
}

我做错了什么?

【问题讨论】:

  • catchError 是什么?它应该在pipe 里面。
  • catchError.catch 的可出租版本,应该在.pipe 中。

标签: angular rxjs rxjs5


【解决方案1】:

记住你的括号。你返回pipe 结果和catchEror 结果除以,

return this.http.get(URL)
  .pipe(map(res => res)),
  catchError(this.handleServerError);

将一个括号放在自己的位置:

return this.http.get(URL)
  .pipe(
    map(res => res),
    catchError(this.handleServerError)
  );

【讨论】:

  • catch和catchError有什么区别?
  • catchError 将在 RxJS 5.5+ 的 pipe() 内部使用而不是 catch
【解决方案2】:

我不认为你接受的答案是正确的。

使用管道语法,我相信应该是这样的:

return this.http.get(URL)
  .pipe(

    map(res => doStuff(res)),

    catchError(err => {
      this.handleServerError(err);
      return this.resDummyData;
    })

  );

当使用 catchError 操作符时,你需要再次返回一个带有订阅期望格式的数据的 observable。否则,如果您在下游订阅中的逻辑因缺少实际的 http 响应数据而失败,那么捕获错误将无济于事......

或者,根据您的用例,您可能希望使用其他 rxjs 运算符(例如 retry 或 retryWhen)来代替 catchError。

好文章:Simple Error Handling in RxJS

【讨论】:

    【解决方案3】:

    您的管道不正确。请改成:

    getProjectInfo(id): Observable<any> {
        const URL = `${this.API}/${id}`;
        return this.http.get(URL)
          .pipe(map(res => res)
                .catch(err => this.handleError('getProjInfo', URL)));
    }
    

    正如马丁所说,它应该在管道内。

    【讨论】:

    • 是的,您需要导入它。以为你已经导入了它。
    • 您的catch 似乎是catch 用于map 功能而不是http.get
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多