简体   繁体   中英

How to catch error in RxJS 5.5

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?

Keep in mind your brackets. You return pipe result and catchEror result divided by , :

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

Place one bracket to own place:

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

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

Your Piping is incorrect. Please change to :

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

As Martin said it should be inside pipe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM