在CodeIgniter中处理纯PHP错误

时间:2018-08-23 16:17:48

标签: php codeigniter

我有一个移动应用程序,该应用程序带有使用CodeIgniter开发的API,该API通过Stripe进行付款。

这些付款是递归的,因此我每月向用户收取一次费用。但是某些用户无法付费(例如,如果用户的卡上没有足够的资金),在这种情况下,Stripe会引发异常。

我希望能够在控制器中执行try / catch。现在我有了这段代码:

try {
    $charge = \Stripe\Charge::create(array(
       "amount" => xxx,
       "currency" => "eur",
       "customer" => xxx)
    );
} catch (Exception $e) {
    // If user has insufficient funds, perfom this code
}

最近,我看到catch中的代码从未执行过,并且我看到CI具有自己的错误处理系统,并且我在日志中看到cli运行的控制器的错误显示在此视图上: application/views/errors/cli/error_php.php。那么如何简单地检测我的Stripe代码是否返回异常?

提前感谢您的回答:)

2 个答案:

答案 0 :(得分:1)

尝试为此类异常使用全局名称空间:

  

catch(\ Exception $ e)//注意反斜杠

答案 1 :(得分:1)

请仔细参阅Stripe的API文档。

他们已经非常详细地描述了错误处理。您可以在这里阅读有关内容:https://stripe.com/docs/api/php#error_handling

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
}