1

I want to detect connection errors to the server, so that I can display an appropriate message to the user.

When the back-end server (a Web API) is off, and I'm trying to access a method on this server by using http.get I expect to get a response with a 404 status, or some sort of a connection error. instead I'm getting

"Response with status: 0 for URL: null"

which is not clear. So how can I detect connection error instead?

This is the relevant code:

Login Component:

this.loginService.tryLogin(userName, password).subscribe(_loginStatus => {
  //Some operations
 },
 _err => this.errMsg = _err; // this.errMsg will be displayed to the user
);

Login Service

tryLogin(user: string, pwd: string): Observable<LoginStatus> {
 return this.http.get(this.serverUri + `Login/?username=${user}&password=${pwd}`)
   .map(response => response.json())
   .catch(err => this.handleError(err));
}

private handleError(error: any) {
  const err = (error.json() ? error.json() : error);
  console.log(err);
  return Observable.throw(err);
}
2
  • Have you checked this? Ending single quote is missing after ${pwd} Commented Aug 27, 2017 at 17:21
  • @PadmanabanGokula oops, fixed it now Commented Aug 28, 2017 at 6:16

1 Answer 1

1

You can make use of Http Interceptors here . Using the new HttpClientModule Interceptors are easy in Angular.

import { Observable } from 'rxjs';
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import { HttpErrorResponse } from "@angular/common/http";

@Injectable()
export class AngularInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).do(event => {}, err => {
        if(err instanceof HttpErrorResponse){ // here you can even check for err.status == 404 | 401 etc
            console.log("Error Caught By Interceptor");
            //Observable.throw(err); // send data to service which will inform the component of the error and in turn the user
        }
    });
  }
}

Register this in Appmodule like

providers: [
        [ { provide: HTTP_INTERCEPTORS, useClass: 
              AngularInterceptor, multi: true } ]
    ],

For more info on Http Client and Interceptors check this link

Sign up to request clarification or add additional context in comments.

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.