Async/Await in fetch() 如何处理错误

新手上路,请多包涵

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

已编辑

添加 .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
      });
  };

谢谢

原文由 Exc 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 368
1 个回答

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

如果您对 fetch 的这种限制不满意,请尝试使用 axios。

原文由 Avanthika 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题