angulartypescripterror-handlingrxjs

Catch error thrown from http.get() thats piped


I have the following code inside my auth service:

return this.http
      .get<any>(`${environment().apiUrl}/auth/refresh`, {
        headers: { Authorization: `Bearer ${this.userValue?.refreshToken}` },
      })
      .pipe(
        map(async (data) => {
          let user = this.parseAndReturnUser(data);
          user.refreshToken = this.userValue?.refreshToken;
          this.userSubject.next(user);
          this.startRefreshTokenTimer();
          return data;
        })
      );

But now I want to error handle this function in case the get call throws an error. I tryed to just enclose everything with try catch but that didn't work. I am a bit lost here on what to do.

How can I catch the error that was thrown by this.http.get()?


Solution

  • You can use catchError rxjs operator, then return an observable, or throw an error.

    return this.http
      .get<any>(`${environment().apiUrl}/auth/refresh`, {
        headers: { Authorization: `Bearer ${this.userValue?.refreshToken}` },
      })
      .pipe(
        catchError((error: HttpErrorResponse) => {
          if (err.status === 401 || err.status === 403) {
            // write your logic here!
          }
          return throwError(error.message);
        }),
        map(async (data) => {
          let user = this.parseAndReturnUser(data);
          user.refreshToken = this.userValue?.refreshToken;
          this.userSubject.next(user);
          this.startRefreshTokenTimer();
          return data;
        })
      );