狂饮6.. x和捕获异常/ PHP


Guzzle 6.x and catching exceptions / PHP

我正在放一个restful博客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;
        }   

但是它直接通过了上面的block:-(

)

如果你根本不想让Guzzle 6抛出4xx和5xx的异常,你需要创建一个没有http_errors中间件的处理程序堆栈,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);