5

I have a script that connects to a third party API. It is and should be running on a non-stop loop 24/7 (I use a sleep at the end before restarting the loop).

The problem is that sometimes the third party API gets ddosed or the connection simply drops with this error:

Fatal error: Uncaught exception 'GuzzleHttp\Ring\Exception\ConnectException' with message 'cURL error 7: Failed to connect to xxx.com port 443

Is there any way to "break" on this fatal error to ensure the code is restarted and proceed if the action can be made or must I manually restart each time I get this error?

ace
  • 313
  • 1
  • 5
  • 19
  • 1
    We can't see your code, but it looks like you can just catch the `GuzzleHttp\Ring\Exception\ConnectException` exception in `try/catch` rather than allowing it to exit fatally. – Michael Berkowski Apr 14 '15 at 01:09
  • Hey there. Nicely formulated question, I made some minor changes to correct some grammar mistakes and make it even more straightforward. Welcome to SO! – Félix Adriyel Gagnon-Grenier Apr 14 '15 at 03:11

2 Answers2

6

From Michael's comment

it looks like you can just catch the GuzzleHttp\Ring\Exception\ConnectException exception

like this:

use GuzzleHttp\Ring\Exception\ConnectException;

try {
    // the code which throws the error
} catch( ConnectException $ex ) {
    switch ( $ex->getMessage() ) {
        case '7': // to be verified
            // handle your exception in the way you want,
            // maybe with a graceful fallback
            break;
    }
}

it appears guzzle's ConnectException extends some classes and ultimately extends php's Exception so you can safely use the getCode() method, allowing you to catch an identifier on which you can react accordingly to your needs.

Community
  • 1
  • 1
  • what should I put on the try? This "ConnectException" should only be called when the exception happen to perform the break instead of fatal error – ace Apr 16 '15 at 13:44
  • only the line where you try to connect to the api; eg the line which *throws the error*. That way, all the flow of your program will work as expected, only the line where you try and connect will be replaced by what's present in the catch block – Félix Adriyel Gagnon-Grenier Apr 16 '15 at 14:12
  • I cannot succeed with this way. – Tung Nguyen Oct 12 '22 at 16:37
0

catch ConnectionException as sample code below:

use Illuminate\Http\Client\ConnectionException;
...
try {
    Http::get('<your url>');
}
catch (ConnectionException $e) {
   // Do something with $e for example Log::debug($e->getMessage());
}
Tung Nguyen
  • 223
  • 3
  • 10