【问题标题】:Guzzle 6.x and catching exceptions / PHPGuzzle 6.x 和捕获异常 / PHP
【发布时间】:2017-03-27 02:38:52
【问题描述】:

我正在使用一个宁静的博客 API。 API 中有简单的错误检查。如果 entry_name 或 entry_body 少于 8 个字符,他的响应如下:

{
  "status":"failure",
 "message":{
        "entry_name":"The entry_name field must be at least 8 characters in length.",
        "entry_body": The entry_body field must be at least 8 characters in length." 
        }
}

在我的网页中,我得到了这个:

Type: GuzzleHttp\Exception\ClientException

Message: Client error: `PUT https://www.example.com/api/v1/Blog/blog`   
resulted in a `400 Bad Request` response: {"status":"failure","message":
{"entry_name":"The entry_name field must be at least 8 characters in 
length.","entry_body" (truncated...)

我不明白如何才能在像上面那样喷出错误之前捕获异常。

我想测试失败,如果失败我想显示消息。

这是我必须捕获异常的代码:

这是我的代码:

         try {
              $response = $client->request('PUT', $theUrl);
              $theBody = $response->getBody();
        } catch (RequestException $e) {
            echo $e;
        }   

但它正好驶过上面的块:-(

【问题讨论】:

  • 刚刚粘贴了一些我正在使用的代码,但它没有看到捕获异常。
  • use GuzzleHttp\Exception\RequestException; 在场吗?
  • 我在作曲家只看到这个:“require-dev”:{“guzzlehttp/guzzle”:“~5.0”,“mockery/mockery”:“~0.8”,“phpunit/phpunit”: "~4.0" }, "suggest": { "guzzlehttp/guzzle": "允许实现 Guzzle HTTP 客户端" }, Is GuzzleHttp\Exception\RequestException;不在上面?
  • 让我改写一下:您是否从正确的命名空间导入 RequestException 类?

标签: php json rest api guzzle


【解决方案1】:

如果您根本不希望 Guzzle 6 为 4xx 和 5xx 抛出异常,您需要创建一个 handler stack 而不使用默认添加到堆栈中的 http_errors 中间件:

$handlerStack = new \GuzzleHttp\HandlerStack(\GuzzleHttp\choose_handler());

$handlerStack->push(\GuzzleHttp\Middleware::redirect(), 'allow_redirects');
$handlerStack->push(\GuzzleHttp\Middleware::cookies(), 'cookies');
$handlerStack->push(\GuzzleHttp\Middleware::prepareBody(), 'prepare_body');

$config = ['handler' => $handlerStack]);

$client = new \GuzzleHttp\Client($config);

【讨论】:

    猜你喜欢
    • 2016-10-05
    • 2013-07-13
    • 2016-10-31
    • 2015-03-20
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多