为了账号安全,请及时绑定邮箱和手机立即绑定

PHP 避免重复相同的 try catch

PHP 避免重复相同的 try catch

PHP
慕娘9325324 2021-09-05 20:42:54
我在 Phalcon 3 中使用 PHP 7。我想在一个函数中实现 Stripe 响应。我可以处理类似的错误是。这是代码: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 异常的函数?我的想法是在参数中发送条带函数并在 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    } 你有想法做我想做的事吗?
查看完整描述

1 回答

?
慕容3067478

TA贡献1773条经验 获得超3个赞

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


您可以将其更改为:


return $this->stripeResponse(function() {

    \Stripe\Charge::create([

        "amount" => 100,

        "currency" => "eur",

        "source" => "token",

        "description" => "Description"

    ]);

});


查看完整回答
反对 回复 2021-09-05
  • 1 回答
  • 0 关注
  • 179 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信