0

I wrote an Angular4 http interceptor. It works fine for the request and for non error responses. But I'm not able to intercept an 401 for instance, the interceptor isn't even triggered. Does someone have an idea how to intercept an 401, for instance to forward to the login page?

Here is my code:

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import { PersistenceService, StorageType, IPersistenceContainer } from 'angular-persistence';
import { Router } from '@angular/router';

@Injectable()

export class TokenInterceptor implements HttpInterceptor {

    storageContainer: IPersistenceContainer

    constructor (
        public persistenceService: PersistenceService,
        public router: Router
    ) {
        this.storageContainer = persistenceService.createContainer(
      'org.ptnc.auth', 
      {type: StorageType.SESSION, oneUse: false}
    )
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        req = req.clone({
            setHeaders: {
                Authorization: 'Bearer ' + this.storageContainer.get('jwt')
            }
        })

        return next.handle(req)
        .do(event => {
            if(event instanceof HttpResponse ){
                console.log('intercepts the response', event)
                // this.router.navigate(['/auth/login'])
            }
            if(event instanceof HttpErrorResponse){
                console.log('the real error')
            }
        })
    }

}
1
  • As with other errors in observables, you need to implement .catch. Commented Oct 14, 2017 at 18:48

3 Answers 3

1

If HttpClient throws an error for a response it bubbles up through the observable chain.

You have to use catch on the next.handle(req) observable to catch and handle the error coming from the HttpClient:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // ...
    return next.handle(req)
      .do(event => {
         // ...
      })
      .catch(error => {
        // handle the error;

        // rethrow it
        return Observable.throw(error);
      });
}
Sign up to request clarification or add additional context in comments.

Comments

1

This is an example of a part of my http.service.ts

  get(request: string): Observable<any> {
    return this._http.get(`${this.actionUrl}${request}`)
      .map(res => this.extractData(res))
      .catch(this.handleError);
  }

  private extractData(res: Response) {
    return res.json();
  }

  private handleError(error: Response) {
    console.log('Error', error);
    return Observable.throw(error.json().error || 'Server error');
  }

Hope it helps as well

Comments

1

To intercept HttpErrorResponse using HttpInterceptor you have to make it in the rxjs way using do operator.

import 'rxjs/add/operator/do';

return next.handle(req).do(event => {
    console.log('handle success event');
    return event;
}, error_event => {
    console.log('handle error event, ie 404 or 500');
    return error_event;
});

Note: catch didn't did the trick for me because http errors are not firing errors with throw()

Comments

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.