【问题标题】:How to check if endpoint is working when using GuzzleHTTP使用 GuzzleHTTP 时如何检查端点是否正常工作
【发布时间】:2016-07-28 04:04:20
【问题描述】:

所以我正在与guzzleHttp 合作,我可以获得我所追求的响应并捕获错误。

我遇到的唯一问题是,如果基本 URI 错误,整个脚本将失败...我如何进行某种检查以确保端点实际上已启动?

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

【问题讨论】:

标签: php guzzle


【解决方案1】:

您的查询可能有很多问题,不仅仅是端点已关闭。您的服务器上的网络接口可能会在查询时立即关闭,DNS 可能会关闭,到主机的路由可能不可用,连接超时等。

因此,您绝对应该为许多问题做好准备。我通常会捕获一般的RequestException 并做一些事情(日志记录、特定于应用程序的处理),如果我应该以不同的方式处理它们,还会捕获特定的异常。

此外,还有许多现有的错误处理模式(和解决方案)。例如,如果端点不可用,通常会重试查询。

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

【讨论】:

  • 嗨,我现在得到:遇到 PHP 错误严重性:4096 消息:传递给 mycontroller::{closure}() 的参数 3 必须是 ResponseInterface 的实例,GuzzleHttp\Psr7 的实例\响应给定文件名:controllers/mycontroller.php 行号:72 有什么想法吗?
  • 只需导入接口即可。我没有包含use GuzzleHttp\Psr7\ResponseInterface,因为它只是一个小的sn-p,而不是整个PHP 文件:)
猜你喜欢
  • 2013-08-10
  • 2016-08-29
  • 2015-07-25
  • 1970-01-01
  • 2012-12-12
  • 1970-01-01
  • 2014-01-11
  • 2020-04-23
  • 1970-01-01
相关资源
最近更新 更多