How to check if endpoint is working when using GuzzleHTTP

爱⌒轻易说出口 提交于 2019-12-07 12:13:01

问题


So I am working with guzzleHttp and I can get the responses that I am after and catch errors.

The only problem I am having is that if the base URI is wrong, the whole script fails... how can I do some sort of checking to make sure that the endpoint is actually up?

$client = new GuzzleHttp\Client(['base_uri' => $url]);

回答1:


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.
]);


来源:https://stackoverflow.com/questions/38614534/how-to-check-if-endpoint-is-working-when-using-guzzlehttp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!