如何处理客户端错误(如Guzzle或Stripe PHP Client)

时间:2016-10-04 13:51:33

标签: php symfony stripe-payments

我再次看到自己也遇到了同样的问题:如何处理调用外部API的客户端?

问题在于此。

如果我使用,例如,可能会发生Guzzle,它会抛出一些exceptions。例如,使用Stripe PHP客户端(此处为documentation about errors)。

也会发生同样的情况

所以,问题始终如一:对于我所做的每次通话,我必须捕捉异常并根据其种类采取行动。

典型示例(摘自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));
    }

但是,问题是:如何处理错误?

分析各种异常:

  1. Authentication:我立即提出它,因为它曾经固定不变的事情再次发生:开发人员只需检查访问密钥;
  2. InvalidRequest:有问题,请稍后再说;
  3. rateLimit:我应该实施某种指数退避as suggested in the documentaion
  4. Network communication:我真的不知道该怎么做才能模拟它
  5. Card:我现在还没有研究过这个问题:我想首先解决其他问题,特别是第2点和第4点。
  6. 所以,请参阅elseif (\Stripe\Error\InvalidRequest):如果引发此异常,我应该怎么做?在我写的评论中,如果我处于开发模式,我可以提出异常,而如果我不是,我应该记录错误......但是,这是处理问题的正确方法吗?

    所以,最后,并且由于我不太清楚如何继续讨论,我该如何处理这样的错误? xaples与Stripe Api一起使用,但同样适用于Guzzle异常,以及许多其他使用异常的库。

    是否有关于如何处理这种情况的某种指导?一些最佳做法?从中可以获得灵感的一些例子?任何建议或正确的方向表示赞赏。谢谢。

1 个答案:

答案 0 :(得分:0)

Middleware FTW !!

这是你做的。

创建对象时,还要创建一个中间件,然后将其注入。

$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:当我说“做你需要的”时,我的意思是抛出你的自定义异常或你需要做的任何事情