gpt4 book ai didi

php - 抽象 try/catch PHP - strip 错误处理

转载 作者:行者123 更新时间:2023-12-03 07:53:27 25 4
gpt4 key购买 nike

我正在处理来自 Stripe API 的错误 - 使用 Stripe 文档中提供的标准 try/catch block 一切正常:

try {

// Use Stripe's library to make requests...

} catch(\Stripe\Error\Card $e) {

//card errors

$body = $e->getJsonBody();
$err = $body['error'];

print('Status is:' . $e->getHttpStatus() . "\n");
print('Type is:' . $err['type'] . "\n");
print('Code is:' . $err['code'] . "\n");
print('Param is:' . $err['param'] . "\n");
print('Message is:' . $err['message'] . "\n");

} catch (\Stripe\Error\RateLimit $e) {
// Too many requests made to the API too quickly
} catch (\Stripe\Error\InvalidRequest $e) {
// Invalid parameters were supplied to Stripe's API
} catch (\Stripe\Error\Authentication $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (\Stripe\Error\ApiConnection $e) {
// Network communication with Stripe failed
} catch (\Stripe\Error\Base $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
}

但是,这是很多代码,我发现自己在重复它。我对如何整理它有点困惑。像这样的东西是理想的:
try {

// Use Stripe's library to make requests...

} // catch all errors in one line

最佳答案

有一个为您处理它的函数:

function makeStripeApiCall($method, $args) {
try {
// call method
} catch (...) {
// handle error type 1
} catch (...) {
// handle error type 2
} ...
}

现在:
  • 如何通过$method ?有几种方法可以做到这一点;例如:
    $method = 'charge';
    $this->stripe->{$method}($args);
    $method = [$stripe, 'charge'];
    call_user_func_array($method, $args);
    $method = function () use ($stripe, $args) { return $stripe->charge($args); };
    $method();

    选择最适合您的情况。
  • 如何准确处理错误?

    您应该捕获特定的 Stripe 异常并将它们适本地转换为您自己的内部异常类型。您希望以不同的方式处理几种广泛类型的问题:
  • 错误的请求,例如卡被拒绝:你想直接在调用业务逻辑代码中捕获这些错误,并根据具体问题做一些事情
  • 服务中断,例如Stripe\Error\ApiConnection或速率限制:除了稍后再试之外,你不能做太多事情,你会想在更高的地方捕捉这些错误并向用户显示“抱歉,稍后再试”消息
  • 错误的配置,例如Stripe\Error\Authentication :没有什么可以自动完成的,您可以向用户显示 500 HTTP 服务器错误,敲响警钟并让 devop 修复身份验证 key

  • 这些基本上是您想要在内部定义然后适当捕获它们的异常类型。例如。:
    ...
    catch (\Stripe\Error\ApiConnection $e) {
    trigger_error($e->getMessage(), E_USER_WARNING);
    throw new TransientError($e);
    }
    ...

    毕竟,您将减少 API 调用,如下所示:
    try {
    return makeStripeApiCall('charge', $args);
    } catch (BadRequestError $e) {
    echo 'Card number invalid: ', $e->getMessage();
    }
    // don't catch other kinds of exception here,
    // let a higher up caller worry about graver issues

    关于php - 抽象 try/catch PHP - strip 错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44946372/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com