Kumail Hussain
Kumail Hussain

Reputation: 879

Http interceptor for error with status 500 in Angular2

I want to intercept my Http response error with status code 500, but I am getting this in my response:

Response {_body: ProgressEvent, status: 0, ok: false, statusText: "", headers: Headers, …}
headers: Headers {_headers: Map(0), _normalizedNames: Map(0)}
ok: false
status: 0status
Text: ""
type: 3
url: null
_body: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …}
__proto__: Body

But in my console I am getting :

zone.js:2019 GET http://127.0.0.1:5000/todos 500 (INTERNAL SERVER ERROR)

so what I am missing

ExtendedHttpService.component.ts

    import { Injectable } from '@angular/core';
import { Request, XHRBackend, RequestOptions, Response, Http, RequestOptionsArgs, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Router } from '@angular/router';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class ExtendedHttpService extends Http {

    constructor(backend: XHRBackend, defaultOptions: RequestOptions, private router: Router) {
        super(backend, defaultOptions);
    }

    request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
        //do whatever
        return super.request(url, options).catch(this.catchErrors());
    }

    private catchErrors() {
        return (res: Response) => {
            console.log(res)//shown the response above
            if (res.status === 500) {

                // this.router.navigate(['logout']);

            }
            return Observable.throw(res);
        };
    }
}

this is my get call:

import { Headers, Http, Response } from '@angular/http';
import { Injectable } from '@angular/core';
import { RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { apiIp } from '../../api.config';

@Injectable()

export class  HttpService {

    constructor(private http: Http) {}

    get(url: string): Observable<any[]> {
        const headers = new Headers({'Content-Type': 'application/json'});
        const options = new RequestOptions({headers});

        return this.http.get(`${url}`, options)
            .map(res => res.json())
            .catch(this.handleError);
    }
   }

what I am missing in my interceptor as my Http Interceptor works fine for status code 400 -499 any help will be appreciated

Upvotes: 2

Views: 3074

Answers (0)

Related Questions