Handling HTTP errors
Handling errors in HTTP requests would typically require an inspection of the information returned in the error response object manually. RxJS provides the catchError
operator to simplify that. In conjunction with the pipe
operator, it can catch potential errors that may occur when initiating an HTTP request:
getHeroes(): Observable<Hero[]> {   return this.http.get<Hero[]>(this.heroesUrl).pipe(     catchError((error: HttpErrorResponse) => {       console.error(error);       return throwError(error);     })   ); }
The signature of the catchError
method contains the actual HttpErrorResponse
object that is returned from the server. After catching the error, we use another operator, named throwError
, which re-throws the error as an observable. In this way, we make sure that the stream will not...