在我的AWS日志中,我有这样的条目:
[Wed Feb 06 10:12:22.306730 2019] [php7:error] [pid 28445] [client 172.31.10.7:55646] PHP致命错误:未捕获错误:在/ var / app / current / project中找不到类'comet_cache' - 网站-WordPress的/可湿性粉剂内容/亩-插件/彗星缓存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显着更改为版本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
}
此外,Error
和Exception
类都实现了Throwable
接口,因此您可以直接捕获它:
<?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");