0

In my application I have some methods returning an Observable:

public myMethodReturningObs(...): Observable {
  return this.http.get(...); // this will return an Observable
}

then I call this method in several places around my application:

this.service.myMethodReturningObs().subscribe(
 (data) => { /* do something with data */ },
 (error) => { console.log('Error!'); }
);

// ...

this.service.myMethodReturningObs().subscribe(
 (data) => { /* do something else with data */ },
 (error) => { console.log('Error!'); }
);

I was wondering if there is a way inside myMethodReturningObs(...) to attach the a default error handling function, which in my example would be console.log('Error!');, so I don't have to repeat it every time I subscribe to the Observable returned by myMethodReturningObs(...).

Ideally I need something like:

public myMethodReturningObs(...): Observable {
  return this.http.get(...)
   .onError({ console.log('Error!'); }); // this will return an Observable
}

so then I can just do:

this.service.myMethodReturningObs().subscribe(
 (data) => { /* do something with data */ }
);

// ...

this.service.myMethodReturningObs().subscribe(
 (data) => { /* do something else with data */ }
);

1 Answer 1

2

You can catch error in base observable, log it and propogate further

public myMethodReturningObs(...): Observable {
  return this.http.get(...)
        .catch(e => {
          // log error
          console.error('Failed', e);
          // return same error, so subscriptions also fail
          return Rx.Observable.throw(e)
        });
}
Sign up to request clarification or add additional context in comments.

3 Comments

it works, but now my unit test are broken: TypeError: Cannot read property 'catch' of undefined
Seems you mocked http service and it return undefined. You can adjust it to return empty Observable.
done it, but now I'm getting another error: Expected $[0] to be a kind of ScalarObservable, but was Observable({ _isScalar: false, source: ScalarObservable({ _isScalar: true, value: 'mock', scheduler: null }), operator: CatchOperator({ selector: Function, caught: <circular reference: Object> }) }).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.