【问题标题】:Exception not caught on PHP5.6 serverPHP5.6 服务器上未捕获异常
【发布时间】:2016-10-03 09:24:56
【问题描述】:

我对我目前开发的网络应用程序有点卡住了。我决定更谨慎地将异常与 try/catch-blocks 一起使用

尽管如此;我使用 PHP7 在本地开发,当我刚刚将应用程序上传到 PHP5 服务器 时,所有这些异常都不再被捕获。相反,脚本执行会因致命错误而停止。我读过一些关于 PHP7 异常的重大变化,但我发现的所有信息都非常模糊。

脚本停止不是什么大问题,但在这种情况下捕获和“修改”错误非常重要,因为脚本是通过 AJAX 调用运行的,并且必须返回 JSON 格式的错误消息。

主文件:

try {

    if (!$this->validateNonce($this->postParams['upload-nonce']))
    throw new Exception('Upload failed because nonce could not be verified.');

    new FloImage(
        $this->postParams['basename'],
        true,
        $this->fileParams['uploadfile']
    );

} catch (Throwable $e) {

    echo json_encode(array('error' => $e->getMessage()));
    die();

}

FloImage() 会检查一些信息(名称、文件大小等),并在发生错误时以这种方式抛出异常:

throw new Exception(_('My error message.'));

如果能提供有关如何使 try-catch-block 与 PHP5 一起工作的帮助,我们将不胜感激!提前谢谢你...

【问题讨论】:

  • 您遇到的致命错误是什么?
  • 我总是得到我抛出的错误。致命错误:我的消息。
  • Throwable 是 PHP7 中的基本接口 -> docs 我认为你无法理解它,因为Exception 没有实现 PHP5 中的接口
  • 谢谢!我必须使用什么才能让它与 PHP5 和 PHP7 一起工作? “例外 $e”?
  • Exception $e 应该可以工作,因为大多数异常都来自Exception。当你抛出 Exception 时,它无论如何都可以在 PHP7 和 PHP5 中工作。

标签: php exception error-handling


【解决方案1】:

Throwable是PHP7中引入的接口。来自manual 它声明:

Throwable 是 PHP 7 中可以通过 throw 语句抛出的任何对象的基本接口,包括错误和异常。

因此,如果您想在 PHP5 中使用您的代码,您必须捕获 Exception 本身。即

try {
    throw new Exception('Some exception');
}
catch (\Exception $e) // use the backslash to comply with namespaces
{
    echo($e->getMessage());
    die();
}

只要抛出的异常源自Exception,这将起作用。即

class SpecialException extends Exception {}

try {
    throw new SpecialException('Some exception');
}
catch (\Exception $e) // use the backslash to comply with namespaces
{
    echo($e->getMessage());
    die();
}

【讨论】:

    【解决方案2】:

    您可能正在寻找set_error_handler(),它用于编写用户定义的错误处理函数。因此,将您的错误处理程序设置在脚本执行的顶部。

    不要忘记在脚本末尾加上restore_error_handler() 以恢复之前的错误处理函数。

    您可以在 set_error_handler() 函数中相应地恢复您的脚本。

    【讨论】:

    • 我想使用 try/catch,而不是错误处理程序。还是谢谢你的建议!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多