php - 尽管使用了 try/catch block ,为什么 PHP 会抛出 fatal error 并破坏 HTTP 500?

标签 php error-handling fatal-error

在我的 AWS 日志中,我有这样的条目:

[Wed Feb 06 10:12:22.306730 2019] [php7:error] [pid 28445] [client 172.31.10.7:55646] PHP Fatal error: Uncaught Error: Class 'comet_cache' not found in /var/app/current/project-website-wordpress/wp-content/mu-plugins/comet-cache-ec2-enabler.php:41



当某些特定的 HTTP 500 请求发生时,会记录这些条目。

检查代码后,我发现以下内容(在提到的文件的第 41 行中):
try {
   comet_cache::clear();
} catch(Exception $e) {
   // if comet cache is not activated, we want to continue anyway
}

这基本上是有道理的 - 似乎找不到该类,但如果是这种情况,则应该继续执行。为什么 PHP 会停止?

最佳答案

你没有抓到是因为你想抓到 \Exception , 但抛出的是 \Error .

考虑到您的错误消息,我会说您使用的是 PHP >= 7(您应该明确指出,错误处理已从版本 5 显着更改为 从版本 5 到版本 7)。

在 PHP >= 7 时,most fatal errors are reported not by raising an error, but by throwing an Error object .

所以你的陈述可以重写为:

try {
    $a = new ClassNotFindable();
}
catch (\Error $e) {
   // do your catching
}

此外,ErrorException类实现 Throwable接口(interface),因此您可以直接捕获它:

<?php

try {
    $a = new NotFound();
}
catch (\Throwable $t) {
    echo "caught!\n";

    echo $t->getMessage(), " at ", $t->getFile(), ":", $t->getLine(), "\n";
}

你可以看到它工作here .

这与 AWS 无关,而只是 PHP 的事情。如果您使用的是 PHP < 7,它仍然不会被捕获,但在这种情况下,因为常见错误不会引发异常。

如果您使用的是 PHP5,为了能够将错误作为异常捕获,您需要设置自定义错误处理程序。 example in the manual似乎很合适:

function exception_error_handler($severidad, $mensaje, $fichero, $línea) {
   if (!(error_reporting() & $severidad)) {
       // Este código de error no está incluido en error_reporting
       return;
   }
   throw new ErrorException($mensaje, 0, $severidad, $fichero, $línea);
}
set_error_handler("exception_error_handler");

关于php - 尽管使用了 try/catch block ,为什么 PHP 会抛出 fatal error 并破坏 HTTP 500?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54551650/

相关文章:

php - 当我使用PHP CodeIgniter更新数据时,会出现错误。但是数据正在保存

linux - APC每次100%碎片

php - 同一云服务上的多个 Azure 虚拟机

swift - Swift 中的错误处理不涉及堆栈展开。这是什么意思?

c++ - 在哪里可以看到与 errno 交互的函数列表?

python - 如何停止致命的Python错误: PyEval_SaveThread: NULL tstate

javascript - PHP 脚本检索 JSON 文件 - 如何将其传递给 JavaScript?

javascript - php显示登录状态消息不更新

java - @ControllerAdvice 类中的信息传递到哪里

ios - iOS 中使用 URL 方案的应用程序间通信