php-尝试,捕获并重试 [英] php - try, catch, and retry
问题描述
有时候我的代码坏了,这超出了我的控制范围
Sometimes my code breaks and it is out of my control
我将如何执行以下操作?
How would I do the following?
try {
//do my stuff
}
catch {
//sleep and try again
}
代码不是很多,所以都是一个函数,所以我不想在不需要的情况下创建并调用另一个函数
The code isn't that much, so it's all one function, so I didn't want to make and call another function if I didn't have to
推荐答案
您可以尝试执行以下操作:
You can try something like this:
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
$NUM_OF_ATTEMPTS = 5;
$attempts = 0;
do {
try
{
executeCode();
} catch (Exception $e) {
$attempts++;
sleep(1);
continue;
}
break;
} while($attempts < $NUM_OF_ATTEMPTS);
function executeCode(){
echo "Hello world!";
}
在这里,我们执行do...while
循环,以便代码至少执行一次.如果executeCode()
函数遇到错误,它将抛出Exception
,该try...catch
块将捕获该函数.然后,catch
块会将变量$attempt
递增1,并调用continue
以测试下一次迭代的while
条件.如果已经进行了五次尝试,则循环将退出并且脚本可以继续.如果没有错误,即未执行catch
块中的continue
语句,则循环将break
,从而完成脚本.
Here, we perform a do...while
loop so that the code is executed at least once. If the executeCode()
function experiences an error, it will throw an Exception
which the try...catch
block will capture. The catch
block will then increment the variable $attempt
by one and call continue
to test the while
condition for the next iteration. If there have already been five attempts, the loop will exit and the script can continue. If there is no error, i.e. the continue
statement from the catch
block is not executed, the loop will break
, thus finishing the script.
请注意set_error_handler
函数的使用,该函数取自此处.我们这样做是为了捕获executeCode()
函数中的所有错误,即使我们自己没有手动抛出错误也是如此.
Note the use of the set_error_handler
function taken from here. We do this so that all errors within the executeCode()
function are caught, even if we don't manually throw the errors ourselves.
如果您认为代码可能多次失败,则在continue
语句之前使用 sleep()
函数可能会有所帮助.降低可能无限循环的速度将有助于降低CPU Usage
.
If you believe your code may fail numerous times, the sleep()
function may be beneficial before the continue
statement. 'Slowing' down the possibly infinite loop will help with lower your CPU Usage
.
让脚本无限运行直到成功为止不是一个好主意,因为在循环的前100次迭代中存在的错误不太可能得到解决,从而导致脚本冻结"向上.通常,最好重新评估要在出现错误的情况下多次运行的代码,并对其进行改进以正确处理可能发生的任何错误.
It is not a good idea to have a script run infinitely until it is successful, since an error that is present in the first 100 iterations of a loop, is unlikely to ever be resolved, thus causing the script to 'freeze' up. More oft than not, it is better to re-evaluate the code that you would like run multiple times in the case of an error, and improve it to properly handle any errors that come its way.
这篇关于php-尝试,捕获并重试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!