我是 PHP 的绝对初学者(我来自 Java),我有以下与如何处理异常相关的问题。
我正在使用 Guzzle 执行对 REST 网络服务的调用,如下所示:
$client = new Client(); //GuzzleHttp\Client
$response = $client->get('http://localhost:8080/Extranet/login',
[
'auth' => [
$credentials['email'],
$credentials['password']
]
]);
$dettagliLogin = json_decode($response->getBody());
如果在响应中我的网络服务返回现有的用户信息,我没有问题。
如果用户不存在我的 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 block 的东西中,这样如果出现 ClientException 被抓到我可以处理它来创建自定义响应吗?
最佳答案
如果您想使用类似于try catch block 。
您可以像此处所述那样使用 Guzzle 异常:
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());
}
}
您可以出于任何目的修改和处理异常。
关于php - 如何正确处理 Guzzle ClientException?我可以将我的调用放入 PHP 中的 Java try catch block 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41934996/