gpt4 book ai didi

PHP 避免重复相同的 try catch

转载 作者:可可西里 更新时间:2023-11-01 00:38:58 26 4
gpt4 key购买 nike

我在 Phalcon 3 中使用 PHP 7。我想在一个函数中实现 Stripe 响应。我可以处理像 that 这样的错误.

代码如下:

try {
// Use Stripe's library to make requests...
} catch(\Stripe\Error\Card $e) {
// Since it's a decline, \Stripe\Error\Card will be caught
$body = $e->getJsonBody();
$err = $body['error'];

print('Status is:' . $e->getHttpStatus() . "\n");
print('Type is:' . $err['type'] . "\n");
print('Code is:' . $err['code'] . "\n");
// param is '' in this case
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
}

每次我需要调用 Stripe 方法时,我都需要实现所有这些 try catch。我怎样才能创建一个包含所有 Stripe 异常的函数?我想到了在参数中发送 strip 函数并在 try 中使用该函数,但它不起作用,因为该函数在函数内部之前执行。

  function stripeResponse($function) {
try {
// Use Stripe's library to make requests...
\Stripe\Stripe::setApiKey("my_key");
$function();
} catch(\Stripe\Error\Card $e) {
// Since it's a decline, \Stripe\Error\Card will be caught
} 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
}
}

return $this->stripeResponse(\Stripe\Charge::create([
"amount" => 100,
"currency" => "eur",
"source" => "token",
"description" => "Description"
]));

你有想法做我想做的事吗?

最佳答案

您调用 $this->stripeResponse 的方式不正确。您将 \Stripe\Charge::create 的响应传递给它而不是可调用对象。

您可以将其更改为:

return $this->stripeResponse(function() {
\Stripe\Charge::create([
"amount" => 100,
"currency" => "eur",
"source" => "token",
"description" => "Description"
]);
});

关于PHP 避免重复相同的 try catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56808808/

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