Catch Guzzle exceptions on connections refused

I am using Guzzle with the following code:

try { $client = new Client(); $result = $client->get("", [ 'headers' => ['Content-Type' => 'application/json'], 'auth' => [$request->ES_LOGIN, $request->ES_PASSWORD], 'allow_redirects' => false, ]); $response['status'] = $result->getStatusCode(); $response['message'] = json_decode($result->getBody()->getContents()); } catch (RequestException $e) { $response['status'] = $e->getResponse()->getStatusCode(); $response['message'] = $e->getMessage(); } 

And it works well however when an user gives the wrong URL for guzzle to process it instead of getting catched in RequestException it gives an 500 error in the server and returns a regular Exception with the message of cURL error 7: Failed to connect to [host] port [port]: Connection refused. Hoe can I make it so that I can catch the error and status code as well to return to the user?

1

2 Answers

Having tried your code, it seems to be throwing an instance of GuzzleHttp\Exception\ConnectException, so change the catch to

} catch (ConnectException $e) { $response['status'] = 'Connect Exception'; $response['message'] = $e->getMessage(); } 

( Adding the appropriate use statement...

use GuzzleHttp\Exception\ConnectException; 

)

Also noticed that it doesn't have $e->getResponse()->getStatusCode(), which is why I've just set it to a fixed string.

9

Since Guzzle has so many Exceptions, i ended up checking which type of exception that guzzle has thrown and constructing a response accordingly:

try { $client = new Client(); $result = $client->get("", [ 'headers' => ['Content-Type' => 'application/json'], 'auth' => [$request->ES_LOGIN, $request->ES_PASSWORD], 'allow_redirects' => false, ]); $response['status'] = $result->getStatusCode(); $response['message'] = json_decode($result->getBody()->getContents()); } catch (ConnectException $e) { $response['status'] = 404; $response['message'] = $e->getMessage(); } catch (RequestException $e) { $response['status'] = $e->getResponse()->getStatusCode(); $response['message'] = $e->getMessage(); } catch (\Exception $e) { $response['status'] = 0; $response['message'] = $e->getMessage(); } 
4

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like