7

I have an angular 2 service which calls an http endpoint in its constructor to retrieve current user. The endpoint throws a 401 if the user has not been authenticated.

My issue is that NG2 logs the exception even though I eat the error.

Here is my service function:

  getVal(): Observable<TestData | boolean> {
    return this.http.get('badUrl', new JsonGetOptions())
      .map(this.jsonParser)
      .catch((error: any) => {
      if (error.status && (error.status === 401 || error.status === 404)) {
        return Observable.of(false);
      }
    return Observable.throw(error);
    });
  }

And here is the service constructor:

  constructor(public http: Http) {
    this.valSource = new ReplaySubject<TestData | boolean>(1);
    this.val$ = this.valSource.asObservable();
    this.getVal()
      .subscribe(val => {
        this.valSource.next(val);
      });
  }

Here is the Plunker

I have simplified the code and changed it to eat HTTP/404 errors to work in plunker.

Everything works as expected. It's just annoying that I see the console error.

Mel
  • 5,837
  • 10
  • 37
  • 42

1 Answers1

0

It seems that your problem is not Rx related. I have tweaked your Plunker to do the following:

return Observable.of('')
    .do(() => console.log('going to do badUrl request'))
    .flatMap(() => this.http.get('badUrl', new JsonGetOptions()))
  .map(this.jsonParser)
  .catch((error: any) => {
    if (error.status && (error.status === 401 || error.status === 404)) {
      console.log('eating error', error);
      return Observable.of(false);
    }
    return Observable.throw(error);
  });

And the output of the console now:

  1. going to do badUrl request
  2. GET https://run.plnkr.co/cQP7WCgUkOmjfvoq/badUrl 40 test-service.ts!transpiled:69
  3. eating error Response ...
Mark van Straten
  • 9,287
  • 3
  • 38
  • 57
  • I still see the 404 error in the console window. I've been researching and looks like there is no way to prevent http errors from showing up in the console window. See http://stackoverflow.com/questions/7035466/check-if-file-exists-but-prevent-404-error-in-console-from-showing-up – darwinsalsa Nov 25 '16 at 05:17