如何正确处理 Guzzle ClientException?我可以在 PHP 中调用类似 Java 的 try catch 块吗?
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());
如果在响应中我的网络服务 return 是现有的用户信息,我没有问题。
如果用户不存在我的 web 服务 return 像这样:
[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 异常:
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 的绝对初学者(我来自 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());
如果在响应中我的网络服务 return 是现有的用户信息,我没有问题。
如果用户不存在我的 web 服务 return 像这样:
[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 异常:
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());
}
}
您可以根据需要修改和处理异常。