How to catch an "undefined index" E_NOTICE error in simpleTest? How to catch an "undefined index" E_NOTICE error in simpleTest? php php

How to catch an "undefined index" E_NOTICE error in simpleTest?


That wasn't really easy but I finally managed to catch the E_NOTICE error I wanted. I needed to override the current error_handler to throw an exception that I will catch in a try{} statement.

function testGotUndefinedIndex() {    // Overriding the error handler    function errorHandlerCatchUndefinedIndex($errno, $errstr, $errfile, $errline ) {        // We are only interested in one kind of error        if ($errstr=='Undefined index: bar') {            //We throw an exception that will be catched in the test            throw new ErrorException($errstr, 0, $errno, $errfile, $errline);        }        return false;    }    set_error_handler("errorHandlerCatchUndefinedIndex");    try {        // triggering the error        $foo = array();        echo $foo['bar'];    } catch (ErrorException $e) {        // Very important : restoring the previous error handler        restore_error_handler();        // Manually asserting that the test fails        $this->fail();        return;    }    // Very important : restoring the previous error handler    restore_error_handler();    // Manually asserting that the test succeed    $this->pass();}

This seems a little overly complicated having to redeclare the error handler to throw an exception just to catch it. The other hard part was correctly restoring the error_handler both when an exception was catched and no error occured, otherwise it just messes with SimpleTest error handling.


There really isn't a need to catch the notice error. One could also test the outcome of 'array_key_exists' and then proceed from there.

http://www.php.net/manual/en/function.array-key-exists.php

Test for false and have it fail.


You'll never catch it within the try-catch block, luckily we have set_error_handler():

<?phpfunction my_handle(){}set_error_handler("my_handle");echo $foo["bar"];?>

You can do anything you want inside my_handle() function, or just leave it empty to silence the notice, although, it's not recommended. A normal handler should be like this:

function myErrorHandler($errno, $errstr, $errfile, $errline)