自定义错误函数不会在php中调用

时间:2015-07-12 12:50:31

标签: php

我正在尝试创建自定义错误函数(遵循教程)。我有:

<?php
  error_reporting(E_ERROR);
  function handleError ($errno, $errstr,$error_file,$error_line){

      echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_line";
      echo "<br />";
      echo "Terminating PHP Script";
      die();

 }

 //set the error handler here, override the default
 set_error_handler("handleError");

 //cause a crash
 myfunction();

?>

但是我的脚本没有调用该函数。它只是打印默认的错误消息。有人可以给我一个指针,指出我在这里做错了吗?我的error_reporting值是错误的吗?

2 个答案:

答案 0 :(得分:1)

您的代码没有任何问题。但是,set_error_handler的功能有限。

来自the PHP documentation

  

使用用户定义的函数无法处理以下错误类型: E_ERROR,E_PARSE,E_CORE_ERROR,E_CORE_WARNING,   E_COMPILE_ERROR,E_COMPILE_WARNING ,以及大多数 E_STRICT 已提出   在调用 set_error_handler() 的文件中。

如果您确实需要捕获编译错误,请参阅上述文档的注释中提到的一种解决方法 - 使用关闭函数:

<?php
error_reporting(E_ERROR);

function handleError($errno, $errstr, $error_file, $error_line) {
      echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_line";
      echo "<br />";
      echo "Terminating PHP Script";
      die();
}

function checkForError() {
    $error = error_get_last();
    if ($error["type"] == E_ERROR) {
        handleError($error["type"], $error["message"], $error["file"], $error["line"]);
    }
}

register_shutdown_function("checkForError");

// cause a crash
myfunction();
?>

请注意,仍将调用默认错误处理程序,因此打印出:

Fatal error: Call to undefined function myfunction() in path\to\file.php on line 24
Error: [1] Call to undefined function myfunction() - path\to\file.php:24
Terminating PHP Script

您可以通过error_reporting(0);禁用错误报告来删除默认邮件。

如果要处理方法执行中的错误(即您已在某处定义了myfunction),原始示例可能已经有效,具体取决于您的具体情况。证明,例如:

<?php
error_reporting(E_ERROR);

function handleError($errno, $errstr, $error_file, $error_line) {
      echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_line";
      echo "<br />";
      echo "Terminating PHP Script";
      die();
}

function myfunction() {
    fopen("nonexistingfile", "r");
}

// set the error handler here, override the default
set_error_handler("handleError");

// cause a crash
myfunction();
?>

这会按预期使用自定义错误处理程序并打印出来:

Error: [2] fopen(nonexistingfile): failed to open stream: No such file or directory - path\to\file.php:12
Terminating PHP Script

答案 1 :(得分:0)

我从w3schools获得此代码,我认为您可能需要触发它

<?php
// A user-defined error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline) {
    echo "<b>Custom error:</b> [$errno] $errstr<br>";
    echo " Error on line $errline in $errfile<br>";
}

// Set user-defined error handler function
set_error_handler("myErrorHandler");

$test=2;

// Trigger error
if ($test>1) {
    trigger_error("A custom error has been triggered");
}
?>