Angular HttpClient error handling difficult

后端 未结 2 1881
执念已碎
执念已碎 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.

提交回复
热议问题