Search code examples
phplaravelguzzle

Catch Guzzle exceptions on connections refused


I am using Guzzle with the following code:

try {
    $client = new Client();
    $result = $client->get("http://{$request->ES_HOST}:{$request->ES_PORT}", [
            '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?


Solution

  • 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.