0

In this pseudo code example

this.someService.someMethod().subscribe(
  (data) =>
  {
      throw Exception
  }
  (err) =>
  {
      throw Exception
  }

How do I catch an error that is thrown inside the subscribe methods?

My specific scenario is that I want to write a unit test for a case that I know will throw an exception

I can't put try/catch logic inside the methods themselves, I want the catch inside the spec.ts file

Edit, just to repeat

I can't put try/catch logic inside the methods themselves, I want the catch inside the spec.ts file

tony
  • 2,178
  • 2
  • 23
  • 40

1 Answers1

2

You can handle the errors thrown by the error handling block using RxJS catchError operator twice like the following:

this.someService
  .someMethod()
  .pipe(
    tap(data => {
      // do something here
      throw Exception;
    }),
    catchError(err => {
      throw Exception;
    }),
    catchError(err2 => {
      // do something with the error thrown from catchError, then return a new Observable
      return EMPTY;
    })
  )
  .subscribe();
Amer
  • 6,162
  • 2
  • 8
  • 34