RxJS how to return Observable with default error handling function

浪子不回头ぞ 提交于 2019-12-11 05:26:43

问题


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:


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)
        });
}


来源:https://stackoverflow.com/questions/47453181/rxjs-how-to-return-observable-with-default-error-handling-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!