为什么无法 PHP 捕获尝试实例化 SoapClient 对象时引起的异常?

Why can't PHP catch exceptions caused when trying to instantiate a SoapClient object?

如果您没有在 php.ini 文件中启用 php_soap.dll 扩展,尝试创建 SoapClient 的实例将导致 PHP 中断。

如果我像这样用 try-catch 块包围实例化,

try{
       $client = new SoapClient ($wsdl, array('cache_wsdl' => WSDL_CACHE_NONE) );   
       $result = $client->{$web_service}($parameters)->{$web_service."Result"};
       return $result;
   }
   catch(Exception $e){
        echo $e->getMessage();
   }

它不会捕捉到异常。相反,它就像在内部 PHP 代码中的某处调用了 die()。有谁知道为什么会这样?

注意:我使用的是 PHP 版本 7.2.1

问题是 PHP 异常处理程序块,即 try-catch 无法处理 trigger_error().

引发的错误

请改用 PHP set_error_handler()

正如 Arvind 已经指出的,错误和异常在 PHP 中是两个不同的东西。 try/catch 仅适用于异常,不适用于错误。

这里稍微解释一下您可以做什么:

错误处理或多或少是为应用程序全局定义的。内置错误处理检查错误的严重性,并根据此记录错误并停止执行。

您可以通过使用 set_error_handler() (http://php.net/set_error_handler) 设置自定义错误处理程序来覆盖此行为。

很常见的方法是定义引发异常的自定义错误处理程序。然后,您就可以在代码中使用 try/catch 处理错误和异常。此处编写了一个完全执行此操作的示例错误处理程序:http://php.net/manual/en/class.errorexception.php.

从那里复制了最有趣的部分:

function exception_error_handler($severity, $message, $file, $line) {
    if (!(error_reporting() & $severity)) {
        // This error code is not included in error_reporting
        return;
    }
    throw new ErrorException($message, 0, $severity, $file, $line);
}
set_error_handler("exception_error_handler");

如果将这段代码放在应用程序开始附近的某个位置,将抛出 ErrorExceptions 而不是引发错误。这应该适用于 SoapClient 错误。