简体   繁体   English

在 Stripe API JS 中使用 Async/Await 进行错误处理

[英]Error handling with Async/Await in Stripe API JS

I'm playing with the Stripe API. Everything works great, but I want to show possible configurations fails in the frontend.我正在玩 Stripe API。一切正常,但我想在前端显示可能的配置失败。 Those fails are handled as an 500.这些失败作为 500 处理。

So this is the condensed code所以这是压缩代码

JS JS

async function initialize() {
    const { clientSecret } = await fetch("index.php?format=json", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id: myid, lang: mylang }),
    }).then((r) => {
        if (r.status >= 400 && r.status < 600) {
            // throw new Error(r.status);
        }
        return r.json()
    }

    ).catch((error) => {
        console.log(error)
    }
    );

    console.log(clientSecret);

}

PHP PHP

header('Content-Type: application/json');
try {
    // code doing some stuff ...
    $output = [
        'secret' => 12345
    ];
    echo json_encode($output);
} catch (Error $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}    

When having a misconfiguration, this is (for example) what the fetch call outputs:当配置错误时,这是(例如)fetch 调用输出的内容:

{
    "error": true,
    "code": 0,
    "message": "The payment method type provided: acss_debit is invalid. This payment method is available to Stripe accounts in CA and US and your Stripe account is in XX.",
}

So how can I catch that error message in JS and display it to the user?那么如何在 JS 中捕获该错误消息并将其显示给用户呢? I tried all kind of stuff in the initialize function.我在初始化 function 中尝试了所有类型的东西。

In your JavaScript code, you can catch the error in the catch block of the fetch function. You can then access the error message from the response object, which is passed as an argument to the catch block.在您的 JavaScript 代码中,您可以在提取 function 的 catch 块中捕获错误。然后您可以从响应 object 中访问错误消息,它作为参数传递给 catch 块。

Here is an example of how you can catch the error and display the error message to the user:以下是如何捕获错误并将错误消息显示给用户的示例:

async function initialize() {
    try {
        const { clientSecret } = await fetch("index.php?format=json", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ id: myid, lang: mylang }),
        }).then((r) => {
            if (r.status >= 400 && r.status < 600) {
                // throw new Error(r.status);
            }
            return r.json();
        });

        console.log(clientSecret);
    } catch (error) {
        console.error(error);
        // Access the error message from the response object
        const { message } = error.response;
        // Display the error message to the user
        alert(message);
    }
}

In this example, the catch block logs the error to the console and displays the error message to the user using an alert.在此示例中,catch 块将错误记录到控制台并使用警报向用户显示错误消息。 You can adjust this code to display the error message in any way that you like, such as by displaying it in a div element or by adding it to the page using JavaScript.您可以调整此代码以按您喜欢的任何方式显示错误消息,例如将其显示在 div 元素中或使用 JavaScript 将其添加到页面。

I hope this helps.我希望这有帮助。 Let me know if you have any questions.如果您有任何问题,请告诉我。


Updates:更新:

It looks like you are using the then method to handle the response from the fetch call, and you are using an if statement to check the status code of the response.看起来您正在使用 then 方法来处理来自 fetch 调用的响应,并且您正在使用 if 语句来检查响应的状态代码。 If the status code is in the range of 400-599, you are not throwing an error or rejecting the promise, so the error will not be caught by the catch block.如果状态码在 400-599 范围内,则不是抛出错误或拒绝 promise,因此错误不会被 catch 块捕获。

To catch the error, you will need to either throw an error or reject the promise in the then block if the status code is in the range of 400-599.要捕获错误,如果状态代码在 400-599 范围内,则需要抛出错误或拒绝 then 块中的 promise。 Here is an example of how you could do this:这是您如何执行此操作的示例:

async function initialize() {
  try {
    const response = await fetch("index.php?format=json", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id: myid, lang: mylang }),
    });
    if (response.status >= 400 && response.status < 600) {
      throw new Error(response.status);
    }
    const { clientSecret } = await response.json();
    console.log(clientSecret);
  } catch (error) {
    console.log(error);
  }
}

Alternatively, you could use the fetch call's reject function to reject the promise if the status code is in the range of 400-599:或者,如果状态代码在 400-599 范围内,您可以使用获取调用的 reject function 来拒绝 promise:

async function initialize() {
  try {
    const response = await fetch("index.php?format=json", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id: myid, lang: mylang }),
    }).then((response) => {
      if (response.status >= 400 && response.status < 600) {
        return Promise.reject(response.status);
      }
      return response.json();
    });
    const { clientSecret } = response;
    console.log(clientSecret);
  } catch (error) {
    console.log(error);
  }
}

Either of these approaches should allow you to catch the error and handle it appropriately in the catch block.这些方法中的任何一种都应该允许您捕获错误并在 catch 块中适当地处理它。

I hope this helps.我希望这有帮助。 Let me know if you have any other questions.如果您有任何其他问题,请告诉我。

I managed to access the catched error message by doing this:我设法通过这样做访问捕获的错误消息:

if (r.status >= 400 && r.status < 600) {

    return r.text()
        .then((text) => {
            throw (JSON.parse(text));
        });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM