我看到自己又遇到了同样的问题:如何处理调用外部api的客户端?
问题是这样的。
例如,如果我使用Guzzle,它可能会抛出一些异常。同样的情况也会发生,例如,Stripe PHP客户端(这里是关于错误的文档)。所以,问题总是一样的:对于我所做的每个调用,我必须捕获异常并根据它们的类型采取行动。
一个典型的例子(取自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
}
所以,如果我对API进行3次调用,我必须重复这个异常处理3次。
我可以更好地创建一个像handleException('Exception $e)
这样的方法来管理异常:
/**
* Handles the Stripe's exceptions.
*
* @param 'Exception $e
*/
private function handleException('Exception $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");
*/
// Authentication with Stripe's API failed
if ($e instanceof 'Stripe'Error'Authentication) {
// Immediately re-raise this exception to make the developer aware of the problem
throw $e;
}
elseif ($e instanceof 'Stripe'Error'InvalidRequest) {
// This should never happen: if we are in development mode, we raise the exception, else we simply log it
die(dump($e));
}
elseif ($e instanceof 'Stripe'Error'RateLimit) {
// Too many requests made to the API too quickly
die(dump(''Stripe'Error'Card error', $e));
}
elseif ($e instanceof 'Stripe'Error'ApiConnection) {
// Network communication with Stripe failed
die(dump(''Stripe'Error'ApiConnection error', $e));
}
elseif ($e instanceof 'Stripe'Error'Card) {
die(dump(''Stripe'Error'Card error', $e));
}
elseif ($e instanceof 'Stripe'Error'Base) {
// Display a very generic error to the user, and maybe send
// yourself an email
die(dump(''Stripe'Error'Base error', $e));
}
elseif ($e instanceof 'Exception) {
// Something else happened, completely unrelated to Stripe
die(dump(''Exception error', $e));
}
但是,问题是:如何处理错误?
分析各种异常:
-
Authentication
:我立即提出它,因为它是一旦固定应该永远不会再发生的事情:开发人员必须简单地检查访问键; -
InvalidRequest
:有问题,见后面; -
rateLimit
:我应该像文档 中建议的那样实现某种指数回退 -
Network communication
:我真的不知道该怎么做,也不知道如何模拟它 -
Card
:我现在还没有研究这个问题,我想先解决其他问题,特别是第2点和第4点。
因此,请参阅elseif ('Stripe'Error'InvalidRequest)
:如果引发此异常,我应该怎么做?在评论中,我写道,如果我处于开发模式,我可以引发异常,而如果我不是,我应该记录错误……但是,这是解决问题的正确方法吗?
所以,明确地说,由于我不知道如何继续讨论,我该如何处理这样的错误?这些例子都是关于Stripe Api的,但同样适用于Guzzle异常,以及许多其他使用异常的库。
是否有一些关于如何处理这种情况的指导?一些最佳实践?有哪些例子可以给我启发?任何建议或正确的方向是赞赏。谢谢你。
中间件!!
这是你要做的。
当你创建你的对象时,你也创建了一个中间件,然后注入它。
$handler = new CurlHandler();
$stack = HandlerStack::create($handler);
$stack->push(ErrorHandlerMiddleware::create(), 'http_error');
那么你的ErrorHandlerMiddleware应该是这样的:
class ErrorHandlerMiddleware {
public static function create() {
return function (callable $handler) {
return function ($request, array $options) use ($handler {
return $handler($request, $options)->then(
function (ResponseInterface $response) use ($request, $handler) {
$code = $response->getStatusCode();
if ($code < 400) {
return $response;
}
$response_body = json_decode($response->getBody(), true);
switch ($code) {
case 400:
// do what you need
case 404:
// do what you need
case 500:
// do what you need
}
},
function (RequestException $e) use ($request, $handler) {
throw new Exceptions'ConnectException('Service Unavailable - Connection Errors '. $e->getMessage(), $request);
}
);
};
};
}
}
现在你不必重复了。
PS:当我说"做你需要的"我的意思是抛出你的自定义异常或任何你需要做的