我的代码片段如下所示 - 正如您所看到的,我有一个try-catch块,但是尽管如此,我仍然会得到一个未被捕获的异常,它会终止整个应用程序。我错过了什么?
try {
$cakeXml = simplexml_load_string($xml);
$parseSuccess = $cakeXml->xpath('//ParseSuccess');
} catch (Exception $ex) {
$response['parseSuccess'] = false;
$response['errors']['ParseError'] = 'An unknown error occurred while trying to parse the file. Please try again';
return $response;
}
2014-12-16 22:45:12 Error: Fatal Error (1): Call to a member function xpath() on a non-object
2014-12-16 22:45:12 Error: [FatalErrorException] Call to a member function xpath() on a non-object
答案 0 :(得分:2)
如果您更仔细地阅读错误消息,您会发现Exception
上没有消息,而是Fatal Error
。 try/catch
语句无法捕获PHP中的致命错误,因为无法从致命错误中恢复。
至于解决此问题,您的错误告诉您$cakeXml
是非对象。一种解决方案是做这样的事情。
try {
$cakeXml = simplexml_load_string($xml);
if (!is_object($cakeXml)) {
throw new Exception('simplexml_load_string returned non-object');
}
$parseSuccess = $cakeXml->xpath('//ParseSuccess');
} catch (Exception $ex) {
$response['parseSuccess'] = false;
$response['errors']['ParseError'] = 'An unknown error occurred while trying to parse the file. Please try again';
return $response;
}
答案 1 :(得分:0)
DOMXPath方法,即xpath或evaluate不会抛出异常。因此,您需要显式验证并抛出异常。
见下面的代码片段:
$xml_1= "";
try {
$cakeXml = simplexml_load_string($xml_1);
if ( !is_object($cakeXml) ) {
throw new Exception(sprintf('Not an object (Object: %s)', var_export($cakeXml, true)));
} else {
$parseSuccess = $cakeXml->xpath('//pages');
print('<pre>');print_r($parseSuccess);
}
} catch (Exception $ex) {
echo 'Caught exception: ', $ex->getMessage(), "\n";
}