I want to use php exceptions to ignore an error that ends up terminating the script

Asked

Viewed 606 times

0

When the user does not have the client installed I get an error terminating the script. How to ignore it with exceptions and continue the script?

PHP Warning: Invalid argument supplied for foreach() in /home/usr/master/app/src/handlers/Iqhandler.php on line 257

PHP Fatal error: Call to a Member Function getChainKey() on null in /home/usr/master/app/src/libaxolotl-php/state/Sessionstate.php on line 177

  • You need to give more details about this ...

  • 1

    Starting with the code. Because no one will answer try{}catch(exception){//faz nada};. Remember that generic questions only deserve generic answers.

1 answer

0


The function foreach() waits for an eternal object like a stdclass or a array.

To avoid the Invalid argument supplied for foreach(), just create a consistent code by checking if the parameter is iterable and has the necessary data for routine execution.

Example for the type array:

$n = 0;
if ($n == 1) {
    $arr = array(1, 2, 3);
}
// Aqui usamos is_array() pois esperamos um array.
if (isset($arr) && is_array($arr) && !empty($arr)) {
    foreach ($arr as $v) {
        echo $v;
    }
}

Example for the type stdclass

$n = 0;
if ($n == 1) {
    $arr = (object)array(1, 2, 3);
}
// Aqui usamos is_object() pois esperamos um stdClass
if (isset($arr) && is_object($arr) && !empty($arr)) {
    foreach ($arr as $v) {
        echo $v;
    }
}

As for the second error, it is probably a consequence of the first error. A chain reaction.

In short, just create code with a consistent stream as there is no way to ignore a fatal error type. This error level may even be hidden but cannot prevent the compiler from interrupting execution.

Note that when PHP runs in CGI mode, a fatal error is dispatched in the same output as display_errors be as OFF.

If you still have doubt, take the test:

$arr = 1;

try{
    foreach ($arr as $v) {
        echo $v;
    }
} catch (Exception $e) {
    // Não funfa para fatal error.
}

The try/catch does not capture type errors fatal error.

  • "Try/catch does not catch fatal error type errors." Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.