error_get_last() returns NULL in PHP 7 when a custom exception handler is set

限于喜欢 提交于 2019-12-02 09:52:50

问题


Ok, this took some time to break it down. Here it is:

There is an included faulty script which is the following for the remainder of this post:

faulty.php

<?php
$a = 4 // missing semicolon
$b = 2;

Then consider the following script for handling the error. Note, that the custom exception handler is initially not registered.

script.php

<?php

// disable default display of errors
ini_set('display_errors', 0);

// register functions
#set_exception_handler('catchException'); // initially not set
register_shutdown_function('catchError');

// define error function
function catchError(){

  echo "PHP version: ".phpversion();

  if(is_null(error_get_last())) echo "<h1>No errors fetched!</h1>";
  else                          echo "<h1>Error fetched:</h1>";

  var_dump(error_get_last());

}

// define exception function (not used in all examples)
function catchException(){}

// include faulty script
include("D:/temp/faulty.php");

Result with no custom exception handler

The results for PHP 5 and 7 are identical. The error_get_last() function returns the last ocurred error (Screenshot).

Result with custom error handler

Now we set a custom function uncommenting the line

set_exception_handler('catchException');

This will work fine in PHP 5, however in PHP 7 the error_get_last() function returns NULL (Screenshot).

Question

Why is this? Especially confusing as the custom exception handler is empty, e.g. not "successfully handling" the error.

How to prevent this?

All the best and thanks for hints!

Update: problem and solution

The thing (not really a problem) is that PHP 7 throws an exception of type ParseError rather then producing an error. Thus, it is best handled with an exception handler. Make a nice exception handler to handle the exception well:

function catchException($e){

  echo "<h1>".get_class($e)."</h1>";
  echo $e->getMessage()."<br>";

}

回答1:


PHP 7 throws a ParseError exception instead of triggering an error of type E_PARSE. The default exception handler seems to trigger an error if an uncaught exception is encountered. However if you replace it with set_exception_handler() it no longer happens unless you do it yourself.

See PHP docs:

PHP 7 changes how most errors are reported by PHP. Instead of reporting errors through the traditional error reporting mechanism used by PHP 5, most errors are now reported by throwing Error exceptions.



来源:https://stackoverflow.com/questions/47728546/error-get-last-returns-null-in-php-7-when-a-custom-exception-handler-is-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!