After quite a bit of messing around, I've got to the point where I can recieve the following body in a 404 error response from my backend. I'm struggling to parse the content into angular so I can use it. I'm know this is simple stuff, so sorry to ask such a basic question. The _body looks like this.
_body: "{\"httpStatus\":404,\"errorType\":\"NotFound\",\"message\":\"Device does not exist!\"}"
These are fine:
console.log("Err = ", err);
Err = Response {_body: "
{\"httpStatus\":404,\"errorType\":\"NotFound\",\"message\":\"Device does not exist!\"}", status: 404, ok: false, statusText: "OK", headers: Headers, …}
and:
console.log("Err Body : ", err._body);
Err Body :
{\"httpStatus\":404,\"errorType\":\"NotFound\",\"message\":\"Device does not exist!\"}
But this doesn't work:
let errorObject = eval(errorString);
Uncaught (in promise): SyntaxError: Invalid or unexpected token
...
var errBody = JSON.parse(errorString);
console.log("JS err body", errBody);
Error: Uncaught (in promise): SyntaxError: Unexpected token \ in JSON at position 1
But I can't figure out how to get the individual fields out. I'm aware that the above efforts are naive and wrong. I'm sure anyone with JS or angular skills can solve this in a minute.
PS cut me some slack. I'm a hardware designer. I'm here because I don't know something, which is always the best reason to ask a question.
Edit:
Thanks for the answers. JSON.parse does not work for me!?
SyntaxError: Unexpected token \ in JSON at position 1
I looked more closely at what you had success with, and I agree it works fine in the console. But it does not work for me in Angular. What did work was:
let errBody = JSON.parse("\"" + err._body + "\"");
Although it seems ridiculous to do. Especially since, afterwards, the result is not quite right:
err body {"httpStatus":404,"errorType":"NotFound","message":"Device does not exist!"}
If I then try to get at errBody.message, it's undefined!... This is totally absurd. What am I doing wrong? How do you guys do this for a living? It's killing me!
errorString? Where is that coming from?JSON.parse('{\"httpStatus\":404,\"errorType\":\"NotFound\",\"message\":\"Device does not exist!\"}');worked for me.