dongquan8753 2017-12-09 12:21
浏览 253
已采纳

设置自定义异常处理程序时,error_get_last()在PHP 7中返回NULL

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条回答 默认 最新

  • dongzhuo7291 2017-12-09 12:29
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型