skip to Main Content

I use the same error handling for multiple rxjs functions:

f1() {
  this.error = undefinded; //*
  obs1$.subscribe({
    next: () => some_code,
    error: error => this.error = error //*
  })
}

f2() {
  this.error = undefinded; //*
  obs2$.subscribe({
    next: () => some_other_code,
    error: error => this.error = error //*
  })
}

how do I factor out the code marked with //*

2

Answers


  1. Here’s one way using a custom operator that wraps the rxjs catchError operator

    function errorHandler (observable) {
      return observable.pipe(catchError(err => {
        console.error(err); // Do whatever you need with the error
        throw err; // rethrow
      }))
    }
    

    Use it like this

    obs1$.pipe(errorHandler).subscribe({
      next: () => {},
      error: error => {} // You can still handle the error downstream if you need to
    });
    
    Login or Signup to reply.
  2. Refer sample below :

    import { Observable, of, throwError } from 'rxjs';
    import { catchError } from 'rxjs/operators';
    
    const yourObservable = /* ... set your observable here ... */;
    
    yourObservable.pipe(
      catchError(error => {
        console.error('An error occurred:', error);
      
        return of('Default Value');   // Return a default value
      })
    ).subscribe(
      nextValue => {
        
        console.log('Next value:', nextValue); // Handle the next value or default value
      },
      error => {
        
        console.error('Observable subscription error:', error); // This block will only be executed if there is an error
      },
      () => {
        console.log('Observable completed successfully'); // This block will be executed when the observable completes
      }
    );
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search