Reputation: 21
I use fetch to get data from my REST service. Once the Response arrives, I want to get the error message, if any, and display it to the user (the user is mostly me).
fetch(address, attributes).then(response => {
if (!response.ok) {
if (response.status === 404) {
return {
text: "Server not found!",
status: "danger"
};
}
return {
text: response.text(),
status: "danger"
};
}
return {
text: "Success!",
status: "success"
};
}
The response.text()
part is the important one: My Backend sends a javax.rs Reponse with a String as entity, e.g. "Error". Here, I want to read it, but response.text() returns only a Promise object which only returns more Promise objects when resolved.
I also tried using {"msg":"[error]"}
and then parse it here as reponse.json().msg
instead, but that didn't work either.
Upvotes: 2
Views: 3011
Reputation: 582
// Success test case
fetch("https://jsonplaceholder.typicode.com/posts/1").then(response => {
if (!response.ok) {
if (response.status === 404) {
return {
text: "Server not found!",
status: "danger"
};
}
return response.text().then(text => {
return {
text: text,
status: "danger"
};
})
}
return {
text: "Success!",
status: "success"
};
}).then(resp => {
console.log("result:", resp);
})
// Failure test case 404
fetch("https://jsonplaceholder.typicode.com/posts/Not_Exist").then(response => {
if (!response.ok) {
if (response.status === 404) {
return {
text: "Server not found!",
status: "danger"
};
}
return response.text().then(text => {
return {
text: text,
status: "danger"
};
})
}
return {
text: "Success!",
status: "success"
};
}).then(resp => {
console.log("result:", resp);
})
// For testing Errors other then 404, i changed 404 error in the code because i couldn't get other HTTP Errors from placeholder api
fetch("https://jsonplaceholder.typicode.com/posts/Not_Exist").then(response => {
if (!response.ok) {
if (response.status === 999) {
return {
text: "Server not found!",
status: "danger"
};
}
return response.text().then(text => {
return {
text: text,
status: "danger"
};
})
}
return {
text: "Success!",
status: "success"
};
}).then(resp => {
console.log("result:", resp);
})
Yes text()
function returns promise object. So one solution could be to use it this way:
fetch(address, attributes).then(response => {
if (!response.ok) {
if (response.status === 404) {
return {
text: "Server not found!",
status: "danger"
};
}
return response.text().then(text => {
return {
text: text,
status: "danger"
};
})
}
return {
text: "Success!",
status: "success"
};
})
The json()
function can be used in the same way:
response.json().then(json => {
return {
text: json.msg,
status: "..."
};
})
Happy coding!
Upvotes: 1