Jump to content

Tell the script to restart from the beginning if it encounters any error


phpchick

Recommended Posts

I keep getting errors that are associated with one-off and one-time occurrences.

 

I want to tell the script to just restart itself from the beginning if it encounters any type of error, whether it by a fatal error, or any other kind.

 

is there a way to do this?

Link to comment
Share on other sites

Not any generic solution.  Any fatal error is going to kill the script before you can do anything about it.  You shouldn't get random fatal errors though.  If your getting a fatal error, you have a problem in your code somewhere you need to fix.

 

Any other errors, like cant connect to a DB or site for instance could be handled in a few ways, such as

 

- encase the code in a loop which will cause it to be re-run in the event of an error:

do {
   $success = true;
   //... main code ...
   //... set $success=false if an error ...
} while (!$success);

 

- In the event of an error, output a page asking the user to reload, maybe output a small JS block to auto-reload the page.

 

Link to comment
Share on other sites

The answer is - it depends. A better approach is to identify these errors and code for them. But, from a practical standpoint, yes you can create a script that will restart if errors are encountered. But, you have to be careful about a possible error that may not be transient (i.e. an error that does not go away). If that happens you would be caught in an infinite loop which could have serious consequences on the rest of your application with regard to performance.

 

For the sake of argument, you could create a while loop that contains the process you need run. Have the loop continue as long as the process does not complete and include a time-limit to prevent infinite loops.

 

Just be sure you do extensive testing before actually implementing anything.

 

Here is an example

$complete = false;
$timeLimit = time() + 120; //2 minutes
while(!$complete && time()<$timeLimit)
{
    //As you run each process that can generate an error,
    // suppress error messages but check for the errors
    $contents = @file_get_content('[url=http://somedomain.com/somedatafile.txt%27%29;]http://somedomain.com/somedatafile.txt');[/url]
    //If result was false restart at condition
    if(!$contents) { continue; }

    //If script completes w/o errors set $complete to true
    if(!$errors) { $complete = true; }
}

Link to comment
Share on other sites

The answer is - it depends. A better approach is to identify these errors and code for them. But, from a practical standpoint, yes you can create a script that will restart if errors are encountered. But, you have to be careful about a possible error that may not be transient (i.e. an error that does not go away). If that happens you would be caught in an infinite loop which could have serious consequences on the rest of your application with regard to performance.

 

For the sake of argument, you could create a while loop that contains the process you need run. Have the loop continue as long as the process does not complete and include a time-limit to prevent infinite loops.

 

Just be sure you do extensive testing before actually implementing anything.

 

Here is an example

$complete = false;
$timeLimit = time() + 120; //2 minutes
while(!$complete && time()<$timeLimit)
{
    //As you run each process that can generate an error,
    // suppress error messages but check for the errors
    $contents = @file_get_content('[url=http://somedomain.com/somedatafile.txt%27%29;]http://somedomain.com/somedatafile.txt');[/url]
    //If result was false restart at condition
    if(!$contents) { continue; }

    //If script completes w/o errors set $complete to true
    if(!$errors) { $complete = true; }
}

 

PHP has a default max_execution_time of 30 seconds, so this would terminate before that time limit is even reached.

Link to comment
Share on other sites

PHP has a default max_execution_time of 30 seconds, so this would terminate before that time limit is even reached.

 

And that value is configurable in the php.ini file. Or you can use set_time_limit(). As I stated that was simply an example - not fully working/validated script.

Link to comment
Share on other sites

Here is one example of a fatal error that occurs. When this happens I just restart the code manually and it will work. i think its just temporary connection issues.

 

 

Fatal error:  Uncaught SoapFault exception: [HTTP] Could not connect to host in /root/file.php:285

Stack trace:

#0 [internal function]: SoapClient->__doRequest('<?xml version="...', 'http://www.xign...', 'http://www.xign...', 1, 0)

#1 [internal function]: SoapClient->__call('GetLastRealTime...', Array)

#2 /root/file.php(285): SoapClient->GetLastRealTimeMetalQuotes(Array)

#3 {main}

  thrown in <b>/root/file.php on line 285

 

 

 

line 285 is

 

$result = $wsdl->GetLastRealTimeMetalQuotes($param);   // this is calling a web service

 

 

 

not sure how implement the recommended fixes in this step. when the fatal error occurs, does it spit out a value somewhere?

 

I saw on php.net that E_ERROR (integer) is a predefined constant for fatal errors. Does this mean that I do...

 

do {

 

the entire code

 

} while (        E_ERROR () =! 1          )     

 

 

I'm just not familiar with the error handling syntax

Link to comment
Share on other sites

$service_header = new SoapHeader('http://www.example.com/services/',

'Header', array("Username" => "usernamegoeshere",

"Password" => "passwordgoeshere",

"Tracer" => ""));

$wsdl = new soapclient('http://www.examples.com/f00.asmx?WSDL');

 

// attach SOAP header

$wsdl->__setSoapHeaders(array($service_header));

 

// call the service: pass the parameters and name of the operation

$param = array('Types' => "XAU", 'Currency' => "USD");

$result = $wsdl->GetLastRealTimeMetalQuotes($param);

Link to comment
Share on other sites

Uncaught exceptions are fatal and your script will die().

 

 

since my error is "Fatal error:  Uncaught SoapFault exception: [HTTP] Error Fetching http headers in /root/fuzzy/htmlmain9.php:126"

 

does that mean there's nothing that can be done but manually restart it?

 

/////////

 

 

nevermind, it's only uncaught because i didn't catch it i believe. - duh

Link to comment
Share on other sites

You are skipping the solutions that you don't understand.

 

Read up on PHP exceptions

http://www.php.net/manual/en/language.exceptions.php

and the try/catch blocks used to deal with them

http://www.webgeekly.com/tutorials/php/how-to-use-try-catch-php-exceptions-to-make-your-code-more-stable/

 

Though I don't really like his nested exceptions. It starts getting quite cluttered.

Link to comment
Share on other sites

nevermind, it's only uncaught because i didn't catch it i believe. - duh

 

Correct, just put your try {} catch(Exception $e) {} block within your infinite loop when you try to execute your SOAP calls. Then you can either echo out $e->getMessage(); to see the error or I'm sure you can just continue; and throw the error out the window.

Link to comment
Share on other sites

will this work? basically I want the line that calls the web service to loop whenever it hits the fatal error. i want it to keep trying to connect until it is successful and then move on to the rest of the code.

 

 

 

 

do { 

try {
$result = $wsdl->GetLastRealTimeMetalQuotes($param);
		}
catch   (Exception $e)
		{
  echo 'Message: ' .$e->getMessage();
  $catcherror =1;
		}

} while ($catcherror != 1); 

//the rest of the program goes here

Link to comment
Share on other sites

You could create a custom error handler that throws exceptions, then use set_error_handler, then use a try catch block along with a goto operator to jump to the top of the script (I hear this is slow), however, I don't see why you want to do this as you WILL end up in an infinite loop because the script will throw an error again unless the code is changed.

 

function custom_error($errno, $errstr, $errfile, $errline, $errcontext)
{
   throw new Exception($errstr);
   return 1;
}
set_error_handler('custom_error', E_ALL);
begin:
try {
   trigger_error('test', E_USER_NOTICE);
}
catch( Exception $e )
{
   goto begin;
}

Link to comment
Share on other sites

the only thing I'm worried about in my implementation is whether or not the code will continue the do-while loop if it hits the error. Can anyone verify this?

 

 

 

do {

 

try {

$result = $wsdl->GetLastRealTimeMetalQuotes($param);

$catcherror = 0;

echo "it connected";

echo"\n";

}

catch  (Exception $e) {

echo 'Message: ' .$e->getMessage();

$catcherror =1;

echo "it didn't connect";

}

 

} while ($catcherror == 1);

Link to comment
Share on other sites

Yes it will.

 

 

do {
   try {
      $result = $wsdl->GetLastRealTimeMetalQuotes($param); // guessing this throws an exception if it errors?
      $catcherror = 0;
      echo "it connected";
      echo"\n";
   }
   catch   (Exception $e)
   {
      //if exception is thrown, this will run, catcherror will be set to 1
      echo 'Message: ' .$e->getMessage();
      $catcherror =1;
      echo "it didn't connect";
   }
} while ($catcherror == 1); // if an error is thrown, this will equal 1 and the code will run again, if no error was encountered, the loop will not run again

You could also do:

echo '<pre>';
try {
   start:
   $result = $wsdl->GetLastRealTimeMetalQuotes($param);
   echo 'Connection established';
}
catch( Exception $e )
{
   echo 'No connection established.'."\r\n";
   goto start;
}
echo '</pre>';

And if you want it for PHP errors (fatal, notice etc...) rather than just exceptions:

function custom_error($errno, $errstr, $errfile, $errline, $errcontext)
{
   throw new Exception($errstr);
   return 1;
}
set_error_handler('custom_error', E_ALL);

echo '<pre>';
try {
   start:
   $result = $wsdl->GetLastRealTimeMetalQuotes($param);
   echo 'Connection established';
}
catch( Exception $e )
{
   echo 'No connection established.'."\r\n";
   goto start;
}
echo '</pre>';

Link to comment
Share on other sites

problems with line 9 and 10....

 

1          do {

2

3 try {

4 $result = $wsdl->GetLastRealTimeMetalQuotes($param);

5 $catcherror = 0;

6 echo "it connected";

7 echo"\n";

8 }

9 catch  (Exception $e) {

10 echo 'Message: ' .$e->getMessage();

11 $catcherror =1;

12 echo "it didn't connect";

13 }

14

15 } while ($catcherror == 1);

 

 

I'm worried about line 9 and 10  because I took it from this example...

 

<?php

//create function with an exception

function checkNum($number)

  {

  if($number>1)

    {

    throw new Exception("Value must be 1 or below");

    }

  return true;

  }

 

//trigger exception in a "try" block

try

  {

  checkNum(2);

  //If the exception is thrown, this text will not be shown

  echo 'If you see this, the number is 1 or below';

  }

 

//catch exception

catch(Exception $e)

  {

  echo 'Message: ' .$e->getMessage();

  }

?>

 

in the example, they manually specify that if the number is greater than 1, to

 

"throw new Exception("Value must be 1 or below");"

 

which is why they use      catch(Exception $e)      later on in the script. In my code, I just use it because its what I saw in the example.  But I'm not sure how to handle it otherwise?

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.