Reputation: 1204
I would like to read the error message inside _body.
Currently, what I do is:
console.log(message._body.error);
However, I am getting undefined.
When I do console.log(message._body);
I get "{"code":141,"error":"This phone number exists already!"}"
var message = {
"_body":"{"code":141,"error":"This phone number exists already!"}",
"status":400,
"ok":false,
"statusText":"Bad Request",
"type":2
};
By the way the following comes form the backend like this and I can't change its format neither remove the double quotes
"_body":"{"code":141,"error":"This phone number exists already!"}"
How can I read the error message?
Upvotes: 0
Views: 91
Reputation: 1823
In your case you need to convert it to json using the json() method after getting the error from your backend.
The following one should work fine with you:
error.json().error
console.log(error.json().error)
Upvotes: 0
Reputation: 2129
You have to fix the json to it's proper form:
var message = {
"_body":'{"code":141,"error":"This phone number exists already!"}',
"status":400,
"ok":false,
"statusText":"Bad Request",
"type":2
};
parse the inner json and use it...
var err = JSON.parse(message._body);
console.log(err.error);
Upvotes: 0
Reputation: 887449
It sounds like you have a property that contains a string of valid JSON.
You need to call JSON.parse()
to convert that to an actual object.
Upvotes: 1
Reputation: 4067
Remove your double quotes. Do this...
"_body":{"code":141,"error":"This phone number exists already!"},
Here is a fiddle...
https://jsfiddle.net/cmht6u8f/1/
Upvotes: 0