0

I have an api call like this:

        this.http.get(url)
            .subscribe(results => {
                ...
            }, (err: any) => {
                console.log('raw error =>', err);
        });

The error on Chrome shows 502 (Bad Gateway), but the error returned from Angular shows status = 0, I would like to show message to the user when this error occurs, but how could I correctly catch the http errors?

enter image description here

Arun Bertil
  • 4,598
  • 4
  • 33
  • 59
rbasniak
  • 4,484
  • 11
  • 51
  • 100

2 Answers2

0

I usually do not subscribe in service, but in component. But this is my code in auth service.

getUser(userId: string) {
    const token = localStorage.getItem('token');
    const headers = new Headers({'Authorization': token});
    return this._http.get('http://localhost:3000/user/' + userId, {headers: headers})           
        .map(response => {
            const data = response.json().obj;
            let user = new User (data.email, data.password, 
                                data.firstName, data.lastName, 
                                data.messages);
            return user;
        })  
        //.catch(error => Observable.throw(error.json()));
        .catch((err) => this.handleError(err));     
}
private handleError(error: Response) {
    if(error.status == 403 ){
        console.error(error + 'Session over. Please log in to continue.');
    }
    console.error(error + 'Session over. Please log in to continue.');
    this._router.navigate(['/']);
    this.logout();

    return Observable.throw(error.json().error || "Server error");
}

In my component, it should be:

this.http.getUser(string: string)
  .subscribe(
     result => { this.result = result;    
   }, 
     error => { console.log('raw error =>', err);
 });

Let me know if I could be more of your assistant.

harold_mean2
  • 238
  • 1
  • 14
-1

Firstly, HTTP Status Code 0 is not really a thing. It only says there was no response received from the server, for whatsoever reasons.

Secondly, HTTP 502 Bad Gateway means that the service you called received an invalid response from the upstream server.

Thirdly, in your specific case I see an Access-Control-Origin issue. This answer gets into details of how to solve it.

Igor Soloydenko
  • 11,067
  • 11
  • 47
  • 90
  • 1
    This is clearly not the answer to the asked question, but merely answers to somebody doing something wrong. I have the same situation and your answer (marked as resolved?) is no help, sorry :( – ramden Nov 12 '17 at 00:04