javascript fetch() 中的 Async/Await 如何处理错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/54163952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Async/Await in fetch() how to handle errors
提问by Exc
I have stripe async code in my React app, and trying to add error handling in my code but have no idea how to handle it. i know how to do it with .then() but async/await is new to me
我的 React 应用程序中有条带异步代码,并尝试在我的代码中添加错误处理,但不知道如何处理它。我知道如何使用 .then() 但 async/await 对我来说是新的
EDITED
已编辑
added .catch() i got errors in network tab in response tab. but i can log it to console?
添加了 .catch() 我在响应选项卡的网络选项卡中出错。但我可以将它记录到控制台吗?
submit = async () => {
const { email, price, name, phone, city, street, country } = this.state;
let { token } = await this.props.stripe
.createToken({
name,
address_city: city,
address_line1: street,
address_country: country
})
.catch(err => {
console.log(err.response.data);
});
const data = {
token: token.id,
email,
price,
name,
phone,
city,
street,
country
};
let response = await fetch("/charge/pay", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}).catch(err => {
console.log(err.response.data);
});
console.log(response);
if (response.ok)
this.setState({
complete: true
});
};
thanks
谢谢
回答by Avanthika
Fetch detects only network errors. Other errors (401, 400, 500) should be manually caught and rejected.
Fetch 只检测网络错误。其他错误(401、400、500)应手动捕获并拒绝。
await fetch("/charge/pay", headers).then((response) => {
if (response.status >= 400 && response.status < 600) {
throw new Error("Bad response from server");
}
return response;
}).then((returnedResponse) => {
// Your response to manipulate
this.setState({
complete: true
});
}).catch((error) => {
// Your error is here!
console.log(error)
});
If you are not comfortable with this limitation of fetch, try using axios.
如果您对 fetch 的这种限制不满意,请尝试使用 axios。
回答by LiraNuna
You can either use try/catchjust like normal, imperative programming:
您可以像普通的命令式编程一样使用try/ catch:
try {
let response = await fetch("/charge/pay", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
});
} catch(error) {
// Error handling here!
}
Or you can mix-and-match .catch()just like you do with promises:
或者你可以.catch()像使用 promise 一样混合搭配:
let response = await fetch("/charge/pay", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}).catch(function(error) {
// Error handling here!
});
回答by Win
Wrap your await with try catch.
用 try catch 包裹你的等待。
try {
let response = await fetch("/charge/pay", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
});
console.log(response);
} catch (error) {
console.log(error);
}
回答by Exc
const data = {
token: token.id,
email,
price,
name,
phone,
city,
street,
country
};
axios
.post("/charge/pay", data)
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err.response.data);
});

