laprof
laprof

Reputation: 1344

How to implement error handling in Angular and RXJS

I would like to perform error handling in the use case method using the subscription. If an error is thrown in the adapter, the handling should be performed in the use case. Unfortunately, the catch does not work with the example below, only the error from the adapter is thrown.

  public checkInUsecase(): void {
    this.checkInAdapter().subscribe(
      (data) => {
        this.logger.debug('Work...');
      },
      (error) => {
        this.logger.error('Error.');
      },
      () => {
        this.logger.debug('Successful.');
      }
    );
  }

  public checkInAdapter(): Observable<boolean> {
    throw new Error('Check in error');
  }

Upvotes: 0

Views: 695

Answers (2)

vaira
vaira

Reputation: 2270

Error is thrown inside an observable. In your example the function is not returning an observable.

public checkInUsecase(): void {
    this.checkInAdapter()
        .pipe(catchError(err) => {
            this.logger.error('Error.');
            throw EMPTY;
        })
        .subscribe((data) => {
            this.logger.debug('Work...');
        });
}

public checkInAdapter(): Observable < boolean > { // this method needs to return an observable
    return new Observable((subscriber) => {
        if (!isAllGood) {
            throw Error('error message'); // error is thrown inside the observable.
        }
    });
}

Upvotes: 1

Leonardo Freire
Leonardo Freire

Reputation: 309

There's a special pipe in Angular that allows you to catch errors in an Observable and react accordingly.

public checkInUsecase(): void {
  this.checkInAdapter()
    .pipe(catchError(err) => {
        this.logger.error('Error.');
        throw EMPTY;
    })
    .subscribe((data) => {
        this.logger.debug('Work...');
    });
}

public checkInAdapter(): Observable<boolean> {
  throw new Error('Check in error');
}

Upvotes: 0

Related Questions