抓 Guzzle Http Exception error

PHP 對 API 發 Request 常用 CURL,然後 Guzzle 是把 CURL 再包一層來做更多的進階操作。

Guzzle 底層使用 CURL,主要拿來呼叫 API、POST、GET 發送 HTTP Request。

不過 Guzzle 的版本也很多,各個版本抓取 Exception 的方式可能也不一樣,此篇使用 Guzzle 7 的版本。

抓 Guzzle Http Exception error

Guzzle 遇到 Server 500 Error 的時候,會直接噴錯誤,就掰了~ 所以要把 Exception 抓到後,再自行處理~

以往想說 catch (\Exception $e) 應該全部抓得到,但是一點用都沒有,於是來翻翻文件~

Guzzle 文件Exceptions — Guzzle Documentation

. \RuntimeException
└── TransferException (implements GuzzleException)
    ├── ConnectException (implements NetworkExceptionInterface)
    └── RequestException
        ├── BadResponseException
        │   ├── ServerException
        │   └── ClientException
        └── TooManyRedirectsException
  • GuzzleHttp\Exception\ClientException for 400 errors
  • GuzzleHttp\Exception\ServerException for 500 errors
  • GuzzleHttp\Exception\BadResponseException 上述兩者皆吃
  • GuzzleHttp\Exception\TooManyRedirectsException too many redirects are followed
  • 不過... 我比較懶,直接用最上層 RequestException 來抓~~
  1. <?php
  2. use GuzzleHttp\Client;
  3. $api_url = 'http://httpbin.org/status/500';
  4. try {
  5. $result = $client->request('GET', $api_url, ['arg_name' => 'arg_value', 'arg2_name' => 'arg2_value']);
  6. } catch (\GuzzleHttp\Exception\RequestException $e) {
  7. if ($e->hasResponse()) {
  8. $response = $e->getResponse();
  9. if ($response->getStatusCode() != 200) {
  10. echo "HTTP Status != 200\n";
  11. }
  12. error_log(print_r($response, true));
  13. }
  14. // 更多訊息可以參考下述
  15. if ($e->hasResponse()) {
  16. $response = $e->getResponse();
  17. var_dump($response->getStatusCode());
  18. var_dump($response->getReasonPhrase());
  19. var_dump((string) $response->getBody()); // JSON
  20. var_dump(json_decode((string) $response->getBody()));
  21. var_dump($response->getHeaders()); // Headers array
  22. var_dump($response->hasHeader('Content-Type'));
  23. var_dump($response->getHeader('Content-Type')[0]);
  24. }
  25. }
  26. ?>

相關網頁

作者: Tsung

對新奇的事物都很有興趣, 喜歡簡單的東西, 過簡單的生活.

發表迴響

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料