簡體   English   中英

Guzzle 6.x和捕獲異常/ PHP

[英]Guzzle 6.x and catching exceptions / PHP

我正在輸入一個寧靜的博客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;
        }   

但它駛過上述街區:-(

如果您根本不希望Guzzle 6拋出4xx和5xx的異常,則需要創建一個沒有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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM