php - 尝试、捕捉和重试

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25002164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:35:48  来源:igfitidea点击:

php - try, catch, and retry

phptry-catch

提问by user3869692

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

代码不多,所以都是一个函数,所以我不想制作和调用另一个函数,如果我不需要的话

回答by noahnu

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!";
}

Here, we perform a do...whileloop so that the code is executed at least once. If the executeCode()function experiences an error, it will throw an Exceptionwhich the try...catchblock will capture. The catchblock will then increment the variable $attemptby one and call continueto test the whilecondition 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 continuestatement from the catchblock is not executed, the loop will break, thus finishing the script.

在这里,我们执行一个do...while循环,以便代码至少执行一次。如果executeCode()函数遇到错误,就会抛出Exceptiontry...catch块将捕获。catch然后该块将变量加一并$attempt调用continue以测试while下一次迭代的条件。如果已经进行了五次尝试,则循环将退出并且脚本可以继续。如果没有错误,即没有执行块中的continue语句catch,则循环将break,从而完成脚本。

Note the use of the set_error_handlerfunction 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.

请注意set_error_handler取自此处的函数的使用。我们这样做是为了executeCode()捕获函数中的所有错误,即使我们自己没有手动抛出错误。

If you believe your code may fail numerous times, the sleep()function may be beneficial before the continuestatement. 'Slowing' down the possibly infinite loop will help with lower your CPU Usage.

如果您认为您的代码可能会失败很多次,那么sleep()continue声明之前该函数可能是有益的。“减慢”可能的无限循环将有助于降低您的CPU Usage.

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.

让脚本无限运行直到它成功并不是一个好主意,因为在循环的前 100 次迭代中出现的错误不太可能得到解决,从而导致脚本“冻结”。通常情况下,最好重新评估您希望在出现错误时多次运行的代码,并对其进行改进以正确处理出现的任何错误。

回答by Reign.85

Simply :

简单地 :

function doSomething($params, $try = 1){
    try{
        //do something
        return true;
    }
    catch(Exception $e){
        if($try <5){
             sleep(10);
             //optionnaly log or send notice mail with $e and $try
             doSomething($params, $try++);
        }
        else{ 
             return false;
        }
    }
}

回答by Amir Fo

Here is an easy algorithm:

这是一个简单的算法:

    do{
        try {
            $tryAgain = false;
            /* Do everything that throws error here */

        }
        catch(Exception $e) {
            $tryAgain = true;
            /* Do error reporting/archiving/logs here */

        }
    } while($tryAgain);

回答by Guy

This library seems cool, it has different backoff strategies you can choose from and keeps you from implementing the retry logic every time.

这个库看起来很酷,它有不同的退避策略可供您选择,并防止您每次都实现重试逻辑。

https://github.com/stechstudio/backoff

https://github.com/stechstudio/backoff

A sample code:

示例代码:

$result = backoff(function() {
    return doSomeWorkThatMightFail();
});

回答by Alex

I don't entirely understand why you would want to, as there is a good chance you will create an infinite loop. However, if the code is likely to succeed after a small sleep, for whatever reason, below is a solution

我不完全理解您为什么要这样做,因为您很有可能会创建一个无限循环。但是,如果代码在小睡后很可能会成功,无论出于何种原因,下面是一个解决方案

while(true){
    // execute the code you are attempting
    if(some condition to signal success){
        break; // exit the loop
    }

    sleep(2); // 2 seconds
}

回答by Varun Nath

To be able to catch an exception you have to first throw one. Something like this.

为了能够捕获异常,您必须先抛出一个异常。像这样的东西。

<?php
function inverse($x) {
    if (!$x) {
        throw new Exception('Division by zero.');
    }
    return 1/$x;
}

try {
    echo inverse(5) . "\n";
    echo inverse(0) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// Continue execution
echo "Hello World\n";
?>

There are certain built in exceptions : http://php.net/manual/en/spl.exceptions.php

有一些内置的例外:http: //php.net/manual/en/spl.exceptions.php