Home > front end >  How to implement error handling in Angular and RXJS
How to implement error handling in Angular and RXJS

Time:01-06

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');
  }

CodePudding user response:

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');
}

CodePudding user response:

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.
        }
    });
}
  •  Tags:  
  • Related