gpt4 book ai didi

php - 捕获包含致命 PHP 错误的 ErrorException

转载 作者:可可西里 更新时间:2023-11-01 13:54:41 24 4
gpt4 key购买 nike

在我自制的 PHP MVC 框架中,我编写了一个小的错误处理程序,将 PHP 错误包装在一个异常中,然后将其抛出。

class ErrorController extends ControllerAbstract {

...

public static function createErrorException($number, $message = NULL, $file = NULL, $line = NULL, array $context = array()) {
throw new ErrorException($message, $number, 0, $file, $line);
}
}

然后使用 set_error_handler() 注册。这工作正常,但 fatal error 除外(没有双关语)。我的自定义错误处理程序仍被调用,但我无法捕获抛出的 ErrorException

此类错误的一个示例是尝试包含一个不存在的文件:

    try {
require 'Controller/NonExistentController.php';
} catch (ErrorException $exc) {
echo $exc->getTraceAsString(); // code never reaches this block
}

我的自定义错误处理程序被调用并抛出异常,但代码从未到达“catch” block 。相反,PHP 生成 HTML(糟糕!):


Warning: Uncaught exception 'ErrorException' with message 'require(Controller/NonExistentController.php): failed to open stream: ...

其次是:

Fatal error: Program::main(): Failed opening required 'Controller/NonExistentController.php' (include_path='.:') in ...

我不想尝试从 fatal error 中恢复,但我确实希望我的代码能够正常退出。在这种情况下,这意味着发回 XML 或 JSON 响应以指示内部错误,因为这是一个 REST 应用程序,而这正是我的客户所期望的。 HTML 响应也很可能会破坏客户端应用程序。

我应该换一种方式吗?

最佳答案

查看有关 require 的文档在 php.net 上:

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 whereas include only emits a warning (E_WARNING) which allows the script to continue.

在您的情况下,您可以借助 register_shutdown_function 处理 fatal error ,这需要 PHP 5.2+:

function customFatalHandler() {
$error = error_get_last();

if( $error === NULL) {
return;
}

$type = $error["type"];
$file = $error["file"];
$line = $error["line"];
$message = $error["message"];

echo "Error `$type` in file `$file` on line $line with message `$message`";
}

register_shutdown_function("customFatalHandler");

这对你也有帮助

  1. error_get_last() and custom error handler
  2. Why doesn't PHP catch a "Class not found" error?

关于php - 捕获包含致命 PHP 错误的 ErrorException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20019548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com