Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 http service. Get detailed error information

Executing Angular2 http call to the offline server doesn't provide much info in it's "error response" object I'm getting in the Observable's .catch(error) operator or subscription error delegate (they are both share the same info actually). But as you can see on the screen shot of the console there's actual error was displayed by zone.js somehow. So, how can I get this specific error info (net::ERR_CONNECTION_REFUSED)?

Thanks.enter image description here

like image 970
rook Avatar asked Aug 13 '16 19:08

rook


2 Answers

Whenever server do not respond, response.status will be always equal to 0 (zero)

{
  type: 3, //ResponseType.Error
  status: 0, // problem connecting endpoint
}

Also note, when you are performing CORS request, but origin (url in browser) is not authorized (not in allowed list of host names configured in remote endpoint) the response would be similar to above, with exception to type attribute which will be equal to 4 = ResponseType.Opaque...

This means, connection was made, but for instance, OPTIONS request returned with headers which do not contain origin or HTTPS request was performed from HTTP origin.

like image 93
Milan Jaric Avatar answered Oct 19 '22 05:10

Milan Jaric


You can handle the error messages so they are easier to read. This can definitely be expanded on too:

public Get() {
    return this.http.get(this.URL).map(this.extractData)
        .catch(this.handleError);
}

public extractData(res: Response) {
    let body = res.json();
    return body || {};
}

public handleError(error: any) {
    let errMsg = (error.message) ? error.message :
        error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg);
    return Observable.throw(errMsg);
}

Check out this part of the docs on error handling.

like image 20
Pezetter Avatar answered Oct 19 '22 05:10

Pezetter