Reputation: 42957
I am an absolute beginner in PHP (I came from Java) and I have the following problem related to how to handle an exception.
I am using Guzzle to perform a call to a REST web service, something like this:
$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.
If the user doesn't exist my web service return something like this:
[2017-01-30 11:24:44] local.INFO: INSERTED USER CREDENTIAL: [email protected] 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.
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?
Upvotes: 3
Views: 9206
Reputation: 4944
If you want to use the similar to try catch block.
You could use the Guzzle Exception like it is stated over here:
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.
Upvotes: 8