Sergej
Sergej

Reputation: 2186

how to implement shared (global) catchError for any observable?

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

Answers (3)

Sayooj V R
Sayooj V R

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

AlexanderFSP
AlexanderFSP

Reputation: 662

Have you tried this one?

(condition ? A : B).pipe(catchError(errorHandler)).subscribe(() => {});

Upvotes: 1

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

Related Questions