Angular 2 http service. Get detailed error information

后端 未结 3 2278
不知归路
不知归路 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: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.

提交回复
热议问题