Search code examples
angularangular-http-interceptors

Angular 4 - interceptor handle net::ERR_CONNECTION_REFUSED


In the code bellow, I try to intercept my http requests. Whenever I can establish a http connection, my interceptor works, but when I got net::ERR_CONNECTION_REFUSED, the event variable is not a instance of HttpResponse, so I can't deal with this kind of error. Here is my code:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this.changeStatus(false);
    this.requests_count++;
    const my_req = req.clone({
        url: API_PATH + req.url
    });
    return next
        .handle(my_req)
        .do(event => {
            if (event instanceof HttpResponse) {
                this.requests_count--;
                if (!this.requests_count)
                    this.changeStatus(true);
            }
        });
}

How can I detect in the interceptor errors like net::ERR_CONNECTION_REFUSED?


Solution

  • Just got it!

    .do(
        event => {
            if (event instanceof HttpResponse) {
                this.requests_count--;
                if (!this.requests_count)
                    this.changeStatus(true);
            }
        },
        error => {
            if (error instanceof HttpErrorResponse) {
                this.requests_count--;
                if (!this.requests_count)
                    this.changeStatus(true);
            }
        }
    );