Angular 2 http service. Get detailed error information

后端 未结 3 2248
不知归路
不知归路 2021-01-04 10:30

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

相关标签:
3条回答
  • 2021-01-04 11:02

    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.

    0 讨论(0)
  • 2021-01-04 11:04

    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.

    0 讨论(0)
  • 2021-01-04 11:15

    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.

    0 讨论(0)
提交回复
热议问题