我有一个async
fetch
调用它调用我的后端来创建具有电子邮件地址的客户。如果成功,返回的 JSON 会发送到doNextThing()
功能。
如果后端返回非 200 状态代码,它也会返回 JSON,例如{"message": "Something went wrong"}
。我想要catch
错误并将该消息发送到console
.
我读过几十个稍微相似的问题并接近答案。到目前为止,我有以下内容,但如果后端的响应是403
例如,状态代码,然后控制台输出“FORBIDDEN”。我think这是因为承诺尚未解决,因此还没有完整的 JSON 响应。或者其他的东西。但我无法弄清楚我错过了什么。
async function createCustomer(email) {
return fetch("/api/create-customer", {
method: "post",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({email: email})
})
.then(function(response) {
if (response.ok) {
return response.json();
} else {
return Promise.reject({
status: response.status,
statusText: response.statusText
});
}
})
.then(function(returned_data) {
doNextThing(returned_data);
})
.catch(function(e) {
console.error(e.statusText);
});
}
就我个人而言,如果您使用的版本支持 async/await 语法,我建议您使用它。它确实简化了代码并允许您轻松使用 try/catch 语法。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await#Browser_compatibility https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await#Browser_compatibility
如果这是一个破坏者的话,它似乎在 IE 中不起作用。
async function createCustomer(email) {
try {
const response = await fetch("/api/create-customer", {
method: "post",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: email })
})
if (response.ok) {
const returnedData = await response.json();
// if doNextThing is an async function, you can await it as well or just return it
doNextThing(returnedData);
} else {
throw {
json: await response.json()
status: response.status,
statusText: response.statusText
};
}
} catch (requestErr) {
// do what you like with the error
// this will be called if you "throw" above or
// if fetch() rejects
if (requestErr.json){
console.error(JSON.stringify(requestErr.json));
}
console.error("Request err:" + requestErr);
}
}
让我知道这是否有帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)