How to catch error in RxJS 5.5

Viewed 7702

I am using Angular 5 along with RXJS 5.5

Before I could just do something like this

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

But now I get this 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>>'.

I've also tried this

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

What am I doing wrong?

3 Answers

I don't think the answer you accepted is correct.

Using pipe syntax, I believe it should be like so:

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

    map(res => doStuff(res)),

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

  );

When using the catchError operator, you'll need to return an observable again with data of the format that the subscription expects. Otherwise, catching the error won't help much if your logic in the downstream subscription fails because the actual http response data is missing...

Alternatively, instead of catchError you may want to use other rxjs operators like retry or retryWhen depending on your use case.

Good article: Simple Error Handling in RxJS

Related