我使用访存从REST服务获取数据。响应到达后,我想获取错误消息(如果有)并将其显示给用户(用户主要是我)。
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"
};
}
response.text()
部分很重要:My Backend发送javax.rs响应,其中以String作为实体,例如“错误”。在这里,我想阅读它,但是response.text()仅返回一个Promise对象,该对象在解析后仅返回更多Promise对象。
我还尝试使用{"msg":"[error]"}
,然后在这里将其解析为reponse.json().msg
,但这也不起作用。
答案 0 :(得分:1)
// 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);
})
是text()
函数返回promise object。因此,一种解决方案是使用这种方式:
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"
};
})
json()
函数可以以相同的方式使用:
response.json().then(json => {
return {
text: json.msg,
status: "..."
};
})
编码愉快!