我想逃避fsockopen
产生的错误,它是这样工作的。
if ($fp = @fsockopen($host,$port,$errCode,$errStr,$waitTimeoutInSeconds)) { //... }
但我一直在尝试其他事情来避免@
,我没有成功。
是否有一个代码我可以用它来等价于这个?
我也试过这样做,只是为了测试的目的:
try{
if ($fp = fsockopen($host,$port,$errCode,$errStr,$waitTimeoutInSeconds)) {
/...
}
//..
} catch (Exception $e){
echo 'Error';
}
它不工作。Warning: fsockopen(): unable to connect to localhost:79 (A connection
attempt failed because the connected party did not properly respond after a period of time or established
connection failed because connected host has failed to respond.
使用set_error_handler()
将所有错误转换为可以稍后捕获的异常:
set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
if(0 === error_reporting())
return false;
throw new PHPException($errno, $errstr, $errfile, $errline, $errcontext);
});
现在你可以捕获PHP错误了:
try {
if ($fp = fsockopen($host,$port,$errCode,$errStr,$waitTimeoutInSeconds)) {
//...
}
//..
} catch ('Exception $e){
echo 'Connection failed: ' , $e->getMessage();
}
echo 'Don''t worry... go on!';
您可以在生产系统中禁用通知和警告(而不是写入日志):
error_reporting(E_ERROR);
在开发环境中,您可能希望所有错误、通知和警告都打开:
error_reporting(E_ALL);
查看错误报告级别:http://php.net/manual/en/errorfunc.configuration.php#ini.error-reporting
编辑:检查错误:
$fp = @fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />'n";
} else {
...
}
我认为如果你正在处理故障场景,那么有意识地使用@来抑制警告是可以的。