Search code examples
angularresponseobservableinterceptorhttp-status-code-401

Angular5 http reponse interceptor unable to read status code


I am trying to intercept http responses and redirect any 401's but the err object below is only returning me the following string. I was expecting to at least find the status code..

401 - Unauthorized Details: Http failure response for http://localhost:4200/api/foo: 401 Unauthorized

I can see in the network tab that a well formed 401 is being returned by the server. Any ideas on how I can read them correctly?

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authRequest = request.clone({
        setHeaders: {
            Authorization: `Bearer ${this.authService.getToken() || ''}`
        }
    });

    return next.handle(authRequest).do(event => { }, err => {
        if (err instanceof HttpErrorResponse && err.status === 401) {
            this.authService.handleAuthentication();
        }
    });
}

Edit: I have just noticed that if i switch off the web server to force a 504 gateway timeout I get the error as a complete string without an error code as well.

504 - Gateway Timeout Details: Http failure response for http://localhost:4200/api/foo: 504 Gateway Timeout


Solution

  • Ok so the problem here was I had a pre-existing error interceptor that was modifying the response before my 401 interceptor. This guy was stringifying everything. Thanks to all the above responses.