代码之家  ›  专栏  ›  技术社区  ›  pixelastic

如何在simpleTest中捕获“未定义索引”E\u通知错误?

  •  16
  • pixelastic  · 技术社区  · 16 年前

    E_NOTICE “未定义索引:foo”。

    expectError() 和 expectException() 没有成功。simpleTest网页表明simpleTest不能捕获编译时PHP错误,但是 紧急通知 似乎是运行时错误。

    3 回复  |  直到 16 年前
        1
  •  19
  •   pixelastic    16 年前

    那真的不容易,但我终于抓住了机会 E_NOTICE error_handler 抛出一个异常,我将在 try{} 声明。

    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();
    }
    

    必须重新声明错误处理程序才能抛出异常来捕获异常,这似乎有点过于复杂。另一个困难的部分是在捕获异常并且没有发生错误时正确地还原错误处理程序,否则它只会破坏SimpleTest错误处理。

        2
  •  6
  •   Robert Brisita    9 年前

    真的没有必要抓住通知错误。还可以测试“array\u key\u exists”的结果,然后从那里继续。

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

        3
  •  2
  •   John Lee    9 年前

    您永远不会在try catch块中捕获它,幸运的是我们设置了\u error \u handler():

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

    您可以在my\u handle()函数中执行任何操作,也可以将其留空以使通知静音,尽管不建议这样做。普通的处理程序应该是这样的:

    function myErrorHandler($errno, $errstr, $errfile, $errline)
    
    推荐文章