dcfg
dcfg

Reputation: 891

error handling in observable or in observer?

I have this method (Angular 9, so Typescript) which is used to retrieve a brend new Json Web Token for authenticate the current user

getNewAccessToken(){
    return this.httpClient.post<Token>(`${this.baseService.baseUrl}auth-token-refresh/`, { refresh: this.getRefreshToken() }, this.baseService.httpOptions).pipe(
      tap((response:Token) => {
        this.cookieService.set(environment.tokenAccessName, response.access, null, '/', null, null, 'Strict');
        this.isLoggedIn.next(true);
      }
  }

When I subscribe to this method, I check for errors like so

this.authService.getNewAccessToken().subscribe(
    res => { //do something with res... },
    error => throw error    //catch error
);

Could I move the error detection directly inside my observable code using pipe and catchError? The code would turn to this

getNewAccessToken(){
    return this.httpClient.post<Token>(`${this.baseService.baseUrl}auth-token-refresh/`, { refresh: this.getRefreshToken() }, this.baseService.httpOptions).pipe(
      tap((response:Token) => {
        this.cookieService.set(environment.tokenAccessName, response.access, null, '/', null, null, 'Strict');
        this.isLoggedIn.next(true);
      },
      catchError(error => {
        throw error;
      })
    ));
  }

I think this is a sort of centralized way of managing errors in observable. Generally, is error handling better on observables or on their observers? What are the pros and cons of these two approaches? Is there any difference in terms of performance? I think the same question can be raised for promises

Upvotes: 1

Views: 1232

Answers (1)

StepUp
StepUp

Reputation: 38134

Yeah, and it is the good practice to move error handling into pipe as it is separation of concern. It separates data retrieving from the presentation of the data.

An example of code of Angular 2 documentation:

return this.http.get<Hero[]>(this.heroesUrl)
    .pipe(
      catchError(this.handleError('getHeroes', []))
    );

Upvotes: 2

Related Questions