Edson Horacio Junior
Edson Horacio Junior

Reputation: 3143

Make ZF2 don't stop on division by zero query

My application builds dynamic reports created by the users, which may produce queries that return division by zero.
When this happens ZF2 catches that with Zend\Db\Adapter\Exception\InvalidQueryException to display the exception and stop my script.

I need to continue the script execution even when that happens, because the application will show 0 in those calculations and the report will still be shown.

I already disabled these settings in config/autoload/local.php and am sure the global.php isn't overwriting them:

'phpSettings'   => array(
    'display_startup_errors' => false,
    'display_errors'         => false,
    'error_reporting'        => 0,
),

'view_manager' => array(
    'display_not_found_reason' => false,
    'display_exceptions'       => false,
),

The script still stops and show my custom "error" page, the only difference is that it hides exception details.

How can I keep the script/application running even when the division by zero occurs?

I already saw other questions talking about display_exceptions=false but as you can see it didn't help me.

I would prefer a solution without making changes to the query creation process, because it is very complex, but am acepting all suggestions.

Upvotes: 0

Views: 106

Answers (2)

Otto Sandström
Otto Sandström

Reputation: 745

You can just Capture the exception yourself by doing a try catch around the the query

try {
    // try to run the query that might throw the exception.
} catch (\Zend\Db\Adapter\Exception\InvalidQueryException $e) {
    // do set the result to zero.
}

Upvotes: 1

mrcendre
mrcendre

Reputation: 1092

In your script, have you considered testing if the denominator equals 0 before it is actually calculated ? If it is, you can skip the calculation and directly return a string or another number. That way you would avoid the division by zero error.


Example

function getStatistics($returned_value) {

    if ($returned_value  == 0) {

      //Cannot compute
      return "Impossible";

    } else {

      //Do the calculation
      return 100/$returned_value; //For example      

    }

}

Upvotes: 0

Related Questions