简体   繁体   English

如何正确处理 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?

I am an absolute beginner in PHP (I came from Java) and I have the following problem related to how to handle an exception.我是 PHP 的绝对初学者(我来自 Java),我有以下与如何处理异常相关的问题。

I am using Guzzle to perform a call to a REST web service, something like this:我正在使用 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());

If in the response my web service returns an existing user information I have no problem.如果在响应中我的 Web 服务返回一个现有的用户信息,我没有问题。

If the user doesn't exist my web service return something like this:如果用户不存在,我的 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"}

So it seems to me that in this case the client throws a ClientException .所以在我看来,在这种情况下,客户端会抛出一个ClientException

My doubt is: can I put this $client->get(...) into something like a Java try catch block so if a ClientException is catched I can handle it creating a custom response?我的疑问是:我可以将这个$client->get(...)放入 Java try catch块之类的东西中,以便如果捕获ClientException我可以处理它创建自定义响应吗?

If you want to use the similar to try catch block .如果要使用类似的try catch 块

You could use the Guzzle Exception like it is stated over here:您可以使用 Guzzle Exception ,就像此处所述:

http://docs.guzzlephp.org/en/latest/quickstart.html#exceptions http://docs.guzzlephp.org/en/latest/request-options.html#http-errors http://docs.guzzlephp.org/en/latest/quickstart.html#exceptions http://docs.guzzlephp.org/en/latest/request-options.html#http-errors

I have plucked the code from the above docs:我从上面的文档中提取了代码:

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());
    }
}

You could modify and handle the exception for whatever purpose you want.您可以出于任何目的修改和处理异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM