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 來抓~~
<?php
use GuzzleHttp\Client;
$api_url = 'http://httpbin.org/status/500';
try {
$result = $client->request('GET', $api_url, ['arg_name' => 'arg_value', 'arg2_name' => 'arg2_value']);
} catch (\GuzzleHttp\Exception\RequestException $e) {
if ($e->hasResponse()) {
$response = $e->getResponse();
if ($response->getStatusCode() != 200) {
echo "HTTP Status != 200\n";
}
error_log(print_r($response, true));
}
// 更多訊息可以參考下述
if ($e->hasResponse()) {
$response = $e->getResponse();
var_dump($response->getStatusCode());
var_dump($response->getReasonPhrase());
var_dump((string) $response->getBody()); // JSON
var_dump(json_decode((string) $response->getBody()));
var_dump($response->getHeaders()); // Headers array
var_dump($response->hasHeader('Content-Type'));
var_dump($response->getHeader('Content-Type')[0]);
}
}
?>