Angular 2 http service. Get detailed error informa

2020-03-01 09:23发布

问题:

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.

回答1:

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.



回答2:

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.



回答3:

Without digging in the code, my expectation is that if the server is unreachable, then no response can be returned from the server. Therefore the Response object remains its initialized state.