dongye8110
2014-12-16 17:00 阅读 61
已采纳

如何捕获require errors + error_handlers

I am trying to use the set_error_handler function to capture require errors.
while my custom error_handler is being used, the context seems completely off, although the trace is correct.

<?php
function error_handler($errno, $errstr, $errfile, $errline){
    throw new Exception($errstr);
}

set_error_handler('error_handler');


try{
    trigger_error("somethign",E_USER_NOTICE);
}catch(Exception $e){
    echo "I got caught";
}


try{
    require "something/that/does/not/exists.php";
}catch(Exception $e){
    echo "I got caught";
}

As can be seen, when I trigger the first error, it triggers the error_handler which in turn is throwing an exception. Which is caught in the first try-catch.

The second time, where I try to include an un-existing file, again the error_handler is used, but the exception is not caught.
What is going on here?

I am using php 5.5.*
Tested in CLI mode.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dsafew1231 dsafew1231 2014-12-16 17:05

    Just read the documentation:

    require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script

    (http://php.net/manual/en/function.require.php)

    That means, the script execution is aborted when this error is encountered. Your custom error handler will be used but throw will be ignore because that assumes further execution which is not allowed at this point.

    点赞 评论 复制链接分享
  • dongyuqi3808 dongyuqi3808 2014-12-16 17:07

    It's important to remember that there's two general types of errors with PHP

    • Processing errors are caught when your program runs
    • Compile errors occur when you have bad syntax or when you try to do something impossible

    In your case, require is a compile error. It will not execute your user defined function because it will never get that far. The compiler can't include the bad file and will fail out.

    点赞 评论 复制链接分享

相关推荐