首页 > 解决方案 > PHP 避免重复相同的 try catch

问题描述

我正在使用 PHP 7 和 Phalcon 3。我想在一个函数中实现 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 异常的函数?我想到了在参数中发送条带函数并在尝试中使用该函数,但它不起作用,因为该函数在函数内部之前被执行。

  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"
    ]));

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

标签: phprefactoring

解决方案


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

您可以将其更改为:

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

推荐阅读