[英]How can I correctly handle a Guzzle ClientException? Can I put my call into something like a Java try catch block in PHP?
我是 PHP 的絕對初學者(我來自 Java),我有以下與如何處理異常相關的問題。
我正在使用 Guzzle 調用 REST Web 服務,如下所示:
$client = new Client(); //GuzzleHttp\Client
$response = $client->get('http://localhost:8080/Extranet/login',
[
'auth' => [
$credentials['email'],
$credentials['password']
]
]);
$dettagliLogin = json_decode($response->getBody());
如果在響應中我的 Web 服務返回一個現有的用戶信息,我沒有問題。
如果用戶不存在,我的 Web 服務將返回如下內容:
[2017-01-30 11:24:44] local.INFO: INSERTED USER CREDENTIAL: pippo@google.com dddd
[2017-01-30 11:24:44] local.ERROR: exception 'GuzzleHttp\Exception\ClientException' with message 'Client error: `GET http://localhost:8080/Extranet/login` resulted in a `401 Unauthorized` response:
{"timestamp":1485775484609,"status":401,"error":"Unauthorized","message":"Bad credentials","path":"/Extranet/login"}
所以在我看來,在這種情況下,客戶端會拋出一個ClientException 。
我的疑問是:我可以將這個$client->get(...)放入 Java try catch塊之類的東西中,以便如果捕獲到ClientException我可以處理它創建自定義響應嗎?
如果要使用類似的try catch 塊。
您可以使用 Guzzle Exception ,就像此處所述:
http://docs.guzzlephp.org/en/latest/quickstart.html#exceptions http://docs.guzzlephp.org/en/latest/request-options.html#http-errors
我從上面的文檔中提取了代碼:
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\RequestException;
try {
$client->request('GET', 'http://localhost:8080/Extranet/login');
} catch (RequestException $e) {
echo Psr7\str($e->getRequest());
if ($e->hasResponse()) {
echo Psr7\str($e->getResponse());
}
}
您可以出於任何目的修改和處理異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.