当我在本地主机上运行我得到这个错误,如果网络断开连接(如果网络是连接它的确定)我想处理这个错误,"错误可以显示",但要处理PHP页面上没有致命错误休息.
Warning: SimpleXMLElement::__construct() [simplexmlelement.--construct]:
php_network_getaddresses: getaddrinfo failed: No such host is known.
in F:\xampp\htdocs\shoptpoint\sections\docType_head_index.php on line 30
Run Code Online (Sandbox Code Playgroud)
但我正在尝试使用try-catch处理.以下是我的代码
$apiurl="http://publisher.usb.api.shopping.com/publisher/3.0/rest/GeneralSearch?apiKey=78b0db8a-0ee1-4939-a2f9-d3cd95ec0fcc&trackingId=7000610&categoryId='5855855'";
try{
new SimpleXMLElement($apiurl,null, true);
}catch(Exception $e){
echo $e->getMessage();
}
Run Code Online (Sandbox Code Playgroud)
如何处理错误,我的页面可以执行项目结束?
使用set_error_handler,您可以执行以下操作将SimpleXMLElement引发的任何通知/警告转换为可捕获的异常.
请考虑以下事项: -
<?php
function getData() {
return new SimpleXMLElement('http://10.0.1.1', null, true);
}
$xml = getData();
/*
PHP Warning: SimpleXMLElement::__construct(http://10.0.1.1): failed to open stream: Operation timed out
PHP Warning: SimpleXMLElement::__construct(): I/O warning : failed to load external entity "http://10.0.1.1"
PHP Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML'
*/
Run Code Online (Sandbox Code Playgroud)
看看我们如何在抛出SimpleXMLElement异常之前得到2个警告?好吧,我们可以将这些转换为这样的异常: -
<?php
function getData() {
set_error_handler(function($errno, $errstr, $errfile, $errline) {
throw new Exception($errstr, $errno);
});
try {
$xml = new SimpleXMLElement('http://10.0.1.1', null, true);
}catch(Exception $e) {
restore_error_handler();
throw $e;
}
return $xml;
}
$xml = getData();
/*
PHP Fatal error: Uncaught exception 'Exception' with message 'SimpleXMLElement::__construct(http://10.0.1.1): failed to open stream: Operation timed out'
*/
Run Code Online (Sandbox Code Playgroud)
祝好运,
安东尼.
| 归档时间: |
|
| 查看次数: |
10499 次 |
| 最近记录: |