Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4.3.3 HttpClient JSON Parsing Error, GET just returns null

Tags:

http

angular

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.

like image 221
Thor Avatar asked Mar 03 '26 16:03

Thor


2 Answers

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

like image 77
DeborahK Avatar answered Mar 05 '26 07:03

DeborahK


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

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

Hope it helps.

like image 29
Dalcof Avatar answered Mar 05 '26 06:03

Dalcof