Javascript fetch()中的Async/Await如何处理错误
我在React应用程序中有条带异步代码,并试图在代码中添加错误处理,但不知道如何处理。我知道如何使用.then()实现它,但async/await对我来说是新事物 已编辑 added.catch()我在响应选项卡的网络选项卡中遇到错误。 但我可以把它记录到控制台吗Javascript fetch()中的Async/Await如何处理错误,javascript,reactjs,asynchronous,fetch,Javascript,Reactjs,Asynchronous,Fetch,我在React应用程序中有条带异步代码,并试图在代码中添加错误处理,但不知道如何处理。我知道如何使用.then()实现它,但async/await对我来说是新事物 已编辑 added.catch()我在响应选项卡的网络选项卡中遇到错误。 但我可以把它记录到控制台吗 submit = async () => { const { email, price, name, phone, city, street, country } = this.state; let {
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
});
};
谢谢用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);
}
您可以使用
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!
}
或者您可以混合搭配.catch()
,就像您对承诺所做的那样:
let response = await fetch("/charge/pay", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}).catch(function(error) {
// Error handling here!
});
Fetch仅检测网络错误。其他错误(401400500)应手动捕获并拒绝
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)
});
wait-fetch(“/charge/pay”,标题)。然后((响应)=>{
如果(response.status>=400&&response.status<600){
抛出新错误(“来自服务器的错误响应”);
}
返回响应;
}).然后((返回的响应)=>{
//你对操纵的反应
这是我的国家({
完全正确
});
}).catch((错误)=>{
//你的错误在这里!
console.log(错误)
});
如果您对这种获取限制不满意,请尝试使用axios。您希望处理哪些错误?请告诉我们您将如何使用
然后
@MattWay而不是相反-如何在异步
/等待
语法中捕获。请查看捕获部分中的更新问题,尝试console.log(错误)。只是一个建议,在第二个位置尝试一下。console.log。catch在网络选项卡和响应选项卡中给了我{“name”:“name”字段是必需的,“email”:“email”无效,“phone”:“phone”字段是必需的,“city”:“city”字段是必需的,“street”字段是必需的,“country”:“country”字段是必需的”}这是可以的,但如何访问它呢??要在前端显示?您所说的“手动捕获并拒绝”是什么意思?请给出一个例子。Fetch不拒绝response.status>=400&&response.status<600
。它将它们视为例外,而不是错误。通过手动拒绝,我指的是抛出catch异常并抛出错误的else部分。很抱歉,我完全错过了if(response.ok)
检入代码(这比比较response.status
更好)。我一定是把第一个然后调用错当成了选项参数,就像问题和其他答案中的片段一样。谢谢,没错,这是一个更简洁的方法。我只是想用我写的代码传达fetch的响应处理。我如何从服务器返回errormessage?仍然无法在前端获取错误。。。我的对象有错误,出现在网络选项卡中…问题是关于获取,在Axios中提供答案不是答案。胜利的关键,谢谢LiraNuna。
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);
});
var handleError = function (err) {
console.warn(err);
return new Response(JSON.stringify({
code: 400,
message: 'Stupid network Error'
}));
};
var getPost = async function () {
// Get the post data
var post = await (fetch('https://jsonplaceholder.typicode.com/posts/5').catch(handleError));
// Get the author
var response = await (fetch('https://jsonplaceholder.typicode.com/users/' + post.userId).catch(handleError));
if (response.ok) {
return response.json();
} else {
return Promise.reject(response);
}
};