Angular HttpClient error handling difficult

后端 未结 2 1882
执念已碎
执念已碎 2021-01-07 10:12

The Angular documentation on the new HttpClient https://angular.io/guide/http has a section \"Getting error details\" where they show an example like below. I have modified

相关标签:
2条回答
  • 2021-01-07 10:29

    I had to look at the Angular source code to understand the possible error conditions. The error object will always be a HttpErrorResponse, but its error property may differ depending on the situation. Here's what can happen when using the default XHRBackend with the default responseType of 'json':

    Response received with HTTP status code indicating error (not 200-299):

    HttpErrorResponse.error will be the body parsed as JSON or if parsing fails, the body as text.

    Response received with good HTTP status code (200-299), but body could not be parsed as JSON:

    HttpErrorResponse.error will be an object typed as HttpJsonParseError with two properties:

    • error: the parse error (of type Error)
    • text: the body text

    No response received due to an XHR network error:

    HttpErrorResponse.error will be an XHR ProgressEvent with the type set to 'error'. (It may be wrongly typed as an ErrorEvent in older versions of TypeScript.)


    Note: Angular does not set a timeout when making requests, nor does it register a timeout event handler. The default XHR timeout is 0, so requests will never time out client-side.

    0 讨论(0)
  • 2021-01-07 10:31

    This might help you

    private handleError(err: HttpErrorResponse) {
        let errorMessage = '';
        if (err.error instanceof Error) {
            // A client-side or network error occurred. 
            errorMessage = `An error occurred: ${err.error.message}`;
        } else {
            // The backend returned an unsuccessful response code.
            // The response body may contain clues as to what went wrong,
            errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
        }
        console.error(errorMessage);
        return Observable.throw(errorMessage);
    }
    
    0 讨论(0)
提交回复
热议问题