2
votes

We're working with Angular 5 and a Spring 2 OAuth Backend. Now when I send an old token it's of course expired. It returns status code: 401 and an error response with invalid token and so on. Now I can't see it in my logs or when I catch the error. I want to get the error so I can at first log it and later on either refresh the token or send him to the Login Page.

Now if i subscribe to the request with:

.subscribe(res => {
    //just random stuff.
    }, err => {
    console.log("error", err);
});

I just see this response in the log with an unknown error like in this image

Could it be failure of the backend? Because i also see in the logs something like a "No 'Access-Control-Allow-Origin' header is present"-error, although it's because of the invalid token.

Although I can see this response code in Google Chrome Dev Tools and a 401 status code.

So I tried to find a solution myself. I've already got an interceptor and tried it with some solutions

return next.handle(authReq)
  .catch(error => {
    console.log("im in here");
    console.log(error);
    return Observable.throw(error);
  });

The Http Service just throws an error that catch is not a function without even logging the error or the "im in here".

I have also tried with the .do after next.handle and I got the same error like catch

.do((event: HttpEvent<any>) => {
    if (event instanceof HttpResponse) {
      // do stuff with response if you want
    }
  }, (err: any) => {
  console.log(err);
    if (err instanceof HttpErrorResponse) {
      if (err.status === 401) {
      }
    }
  });

I've tried with pipe after the http.get but it doesn't work either.

http.get(...).pipe(
  retry(3), // retry a failed request up to 3 times
  catchError(this.handleError) // then handle the error
);
1

1 Answers

2
votes
    import 'rxjs/add/operator/catch';

    Somefunc(){
    this.httpClient
          .get("data-url")
          .subscribe(
            data => console.log('success', data),
            error => console.log('oops', error)
          );
    }


    OR

this.httpClient
      .get("data-url")
      .catch((err: HttpErrorResponse) => {
        // simple logging, but you can do a lot more, see below
        console.error('An error occurred:', err.error);
      });

Should work.