php - 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"
]));
你有想法做我想做的事吗?
解决方案
你打电话的方式$this->stripeResponse
不正确。您传递的是响应\Stripe\Charge::create
而不是可调用的。
您可以将其更改为:
return $this->stripeResponse(function() {
\Stripe\Charge::create([
"amount" => 100,
"currency" => "eur",
"source" => "token",
"description" => "Description"
]);
});
推荐阅读
- android - Android Alpha 内部版本无法登录。我在哪里可以查看日志文件?
- python - 意外的 split() 行为 Python
- python - 划分 2 列并使用结果创建新列
- alexa - 将 alexa 设备限制为只有一项技能?
- symfony - 没有空格的 Symfony 4 字母数字验证
- dc.js - dc.js 带条形和折线的复合图表。在栏上实现单选
- python - 使用实体嵌入和 Keras 功能 API 将文本与分类特征相结合
- java - Java - sc.nextDouble() - 换行
- php - Vimeo API 获取结果为空的请求
- c# - 保存前设置值