Reputation: 2186
Image, I have the next code:
if (something) {
return A;
} else {
return B;
}
A and B, are Observables.
I want to catchError in both of them and handle in the same way.
How to implement this.
For the moment I would write something like this:
const errorHadler = ...;
if (something) {
return A.pipe(
catchError(errorHandler)
)
} else {
return B.pipe(
catchError(errorHandler)
)
}
is it possible to use only one catchError for both observeables?
Upvotes: 1
Views: 190
Reputation: 2363
Create a error handler service .make it as a single ton service by setting providedIn:root . Call this service's errorHandler method where ever you want.
@Injectable({
providedIn: 'root'
})
export class ErrorhandlerService {
errorHandler(){
//logic goes here
}
}
if (something) {
return A.pipe(
catchError(this.errorhandlerService.errorHandler)
)
} else {
return B.pipe(
catchError(this.errorhandlerService.nerrorHandler)
)
}
Advantage of this approach is , you can reuse the service in the entire application.
Upvotes: 1
Reputation: 662
Have you tried this one?
(condition ? A : B).pipe(catchError(errorHandler)).subscribe(() => {});
Upvotes: 1
Reputation: 1040
Hope this will help:
getData(){
if (something) {
return A;
} else {
return B;
}
}
this.getData.subscribe(response=>
{
// if success do logic here
}, error=>{
// Have commonn error handling logic here
});
Hope this helps.
Upvotes: 2