在fetch()中异步/等待如何处理错误 [英] Async/Await in fetch() how to handle errors

查看:399
本文介绍了在fetch()中异步/等待如何处理错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在React应用程序中有条带化异步代码,并且试图在我的代码中添加错误处理,但是不知道如何处理它.我知道如何使用.then()来做,但是async/await对我来说是新的

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

已编辑

添加了.catch()我在响应"选项卡的网络"选项卡中出现错误. 但是我可以将其登录到控制台吗?

added .catch() i got errors in network tab in response tab. but i can log it to console?

    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
      });
  };

谢谢

推荐答案

提取仅检测网络错误.其他错误(401、400、500)应手动捕获并拒绝.

Fetch detects only network errors. Other errors (401, 400, 500) should be manually caught and rejected.

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)
});

如果您对这种提取限制不满意,请尝试使用axios.

If you are not comfortable with this limitation of fetch, try using axios.

这篇关于在fetch()中异步/等待如何处理错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆