抽象的try/catch PHP - 条纹错误处理
问题描述:
我从条纹API处理错误 - 一切使用的条纹文档提供的标准try/catch块正常工作:抽象的try/catch PHP - 条纹错误处理
try {
// Use Stripe's library to make requests...
} catch(\Stripe\Error\Card $e) {
//card errors
$body = $e->getJsonBody();
$err = $body['error'];
print('Status is:' . $e->getHttpStatus() . "\n");
print('Type is:' . $err['type'] . "\n");
print('Code is:' . $err['code'] . "\n");
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
}
然而,这是一个很大的代码,我发现自己重复它。我有点卡在如何把它整理起来。这样的事情将是理想的:
try {
// Use Stripe's library to make requests...
} // catch all errors in one line
答
有一个处理它为您的函数:
function makeStripeApiCall($method, $args) {
try {
// call method
} catch (...) {
// handle error type 1
} catch (...) {
// handle error type 2
} ...
}
现在:
-
如何通过
$method
?有几种方法可以做到这一点;例如:$method = 'charge'; $this->stripe->{$method}($args);
$method = [$stripe, 'charge']; call_user_func_array($method, $args);
$method = function() use ($stripe, $args) { return $stripe->charge($args); }; $method();
选择最适合您的情况。
-
如何正确处理错误?
您应该捕获特定的Stripe异常并根据需要将它们转换为您自己的内部异常类型。有几种广泛类型的问题需要以不同的方式处理:
不良请求,例如,卡拒绝:您希望直接在调用业务逻辑代码中捕获这些错误,并根据特定问题执行某些操作
服务已关闭,例如,
Stripe\Error\ApiConnection
或速率限制:你不能做与那些除了稍后再试,你想不想找个上涨赶上这些错误,并用“对不起,稍后再试”消息错误的配置呈现给用户,例如
Stripe\Error\Authentication
:没有什么可以自动完成,你可以用一个500 HTTP服务器错误向用户呈现,响警钟,并获得devop修复认证密钥
这些基本上是种异常类型你想内部定义,然后适当地捕捉它们。例如: -
... catch (\Stripe\Error\ApiConnection $e) { trigger_error($e->getMessage(), E_USER_WARNING); throw new TransientError($e); } ...
这一切后,你将减少API调用是这样的:
try {
return makeStripeApiCall('charge', $args);
} catch (BadRequestError $e) {
echo 'Card number invalid: ', $e->getMessage();
}
// don't catch other kinds of exception here,
// let a higher up caller worry about graver issues
感谢您的回答 - 这是非常有用的。我的主要问题是传递方法,因为try块会有很大的差异。它可能会收取费用,检索客户,创建订阅,更改订阅计划,添加优惠券 - 所有这些都有不同的参数和元数据。 – Ryan
一个匿名函数应该是最灵活的。 – deceze
谢谢 - 我会研究一下 – Ryan