How to check if endpoint is working when using GuzzleHTTP

时光总嘲笑我的痴心妄想 提交于 2019-12-06 00:08:19

You might have many issues with your query, not only that the endpoint is down. Network interface on your server can go down right at the moment of query, DNS can go down, a route to the host might not be available, a connection timeout, etc.

So you definitely should be ready for many issues. I usually catch a general RequestException and do something (logging, app specific handling), plus catch specific exceptions if I should handle them differently.

Also, there are many existing patterns (and solutions) for error handling. For example, it's usual to retry a query is an endpoint is unavailable.

$stack = HandlerStack::create();
$stack->push(Middleware::retry(
    function (
        $retries,
        RequestInterface $request,
        ResponseInterface $response = null,
        RequestException $exception = null
    ) {
        // Don't retry if we have run out of retries.
        if ($retries >= 5) {
            return false;
        }

        $shouldRetry = false;
        // Retry connection exceptions.
        if ($exception instanceof ConnectException) {
            $shouldRetry = true;
        }
        if ($response) {
            // Retry on server errors.
            if ($response->getStatusCode() >= 500) {
                $shouldRetry = true;
            }
        }

        // Log if we are retrying.
        if ($shouldRetry) {
            $this->logger->debug(
                sprintf(
                    'Retrying %s %s %s/5, %s',
                    $request->getMethod(),
                    $request->getUri(),
                    $retries + 1,
                    $response ? 'status code: ' . $response->getStatusCode() :
                        $exception->getMessage()
                )
            );
        }

        return $shouldRetry;
    }
));

$client = new Client([
    'handler' => $stack,
    'connect_timeout' => 60.0, // Seconds.
    'timeout' => 1800.0, // Seconds.
]);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!