Guzzle 6.x和捕获异常/PHP

Guzzle 6.x和捕获异常/PHP,php,json,rest,api,guzzle,Php,Json,Rest,Api,Guzzle,我正在使用restful博客API。API中有简单的错误检查。如果条目名称或条目正文少于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 character

我正在使用restful博客API。API中有简单的错误检查。如果条目名称或条目正文少于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...)
我不明白在guzzle像上面那样泄漏错误之前如何捕获异常

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

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

这是我的代码:

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

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

如果您根本不希望Guzzle 6为4xx和5xx抛出异常,那么您需要创建一个没有http_错误的中间件,默认情况下该中间件会添加到堆栈中:

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

如果您根本不希望Guzzle 6为4xx和5xx抛出异常,则需要创建一个没有http_错误的中间件,该中间件默认添加到堆栈中:

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

try catch->刚刚粘贴了一点我正在使用的代码,但它看不到捕获异常。是否存在
use GuzzleHttp\exception\RequestException;
present?我在composer中只看到这样一条:“require dev:{“GuzzleHttp/guzzle”:“~5.0”,“mockry/mockry”:“~0.8”,“phpunit/phpunit”:“~4.0”},建议:{“guzzlehttp/guzzle”:“允许实现guzzlehttp客户端”},是GuzzleHttp\Exception\RequestException;不在上面吗?让我重新表述一下:您是否从正确的命名空间导入了
RequestException
类?尝试catch->只是粘贴了我正在使用的代码的一部分,但它没有看到捕获异常。是
使用GuzzleHttp\Exception\RequestException;
存在吗?我只在composer中看到了是:“require dev”:{“guzzlehttp/guzzle”:“~5.0”,“mockry/mockry”:“~0.8”,“phpunit/phpunit”:“~4.0”},建议:{“guzzlehttp/guzzle”:“允许实现guzzlehttp客户机”},是http\Exception\RequestException;不在上面吗?让我重新表述一下:您是否从正确的命名空间导入了
RequestException
类?