Reputation: 2392
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
Upvotes: 0
Views: 924
Reputation: 6706
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();
Upvotes: 2