2016-11-13 58 views
0

我正在打造一個寧靜的博客API。在API中有簡單的錯誤檢查。如果ENTRY_NAME或entry_body少於8個字符,他的反應如下:Guzzle 6.x和捕捉異常/ PHP

{ 
    "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; 
     } 

但它航行權過上述塊:-(

+0

try-catch - > http://php.net/manual/en/language.exceptions.php – Federkun

+0

剛剛粘貼了一段我正在使用的代碼,但沒有看到發現異常。 – user3264461

+0

是'use GuzzleHttp \ Exception \ RequestException;'存在嗎? – Federkun

回答

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