Angular 4.3.3 HttpClient JSON Parsing Error, GET j

2019-05-11 03:29发布

If I get invalid data from an HTTP request using the new HttpClient in Angular 4.3.3, such as this (extraneous commas):

{
  "a": "it is a",
  "b": "it is b",,
}

I get no errors, and the result is null

this.httpClientNew.get<any>('assets/mockjson.json').subscribe(
  (response) => {console.log("NEW RESPONSE:[" + response + "]")},
  (error) => {console.error(error)}
)

Using the old client I can get the JSON parsing error including the exact character where the problem is:

this.httpClientOld.get('assets/mockjson.json').map(
  (response) => {console.log("OLD RESPONSE:[" + response + "]");
    return response.json();
  }
).subscribe(
  (res) => {console.log(res)},
  (err) => {console.error(err)}
)

Which gives the nice error:

SyntaxError: Unexpected token , in JSON at position 39

Is there a way to get this detailed error message with the new Angular 4.3.3 HttpClient? Thanks.

标签: angular http
2条回答
叼着烟拽天下
2楼-- · 2019-05-11 04:10

You can use observe if you're interested in the whole Response:

 this.http.get('…', { observe: 'response' });

Hope it helps.

查看更多
贪生不怕死
3楼-- · 2019-05-11 04:22

The basic answer is "no".

From someone on the Angular team:

"HttpClient delegates parsing to the browser. That doesn't report errors."

So what's to be done if one retrieves a large amount of Json only to get null back? Is there a way to know that it even was a parsing error and not a server problem if all we get back is null? All open questions.

Maybe we need to start an issue for this on github for further discussion? https://github.com/angular/angular/issues

查看更多
登录 后发表回答