Was*_*eem 290 php warnings exception-handling function
我写了这样的PHP代码
$site="http://www.google.com";
$content = file_get_content($site);
echo $content;
Run Code Online (Sandbox Code Playgroud)
但当我删除"http://"时,$site我收到以下警告:
警告:file_get_contents(www.google.com)[function.file-get-contents]:无法打开流:
我尝试过try,catch但它没有用.
Roe*_*oel 477
第1步:检查返回码: if($content === FALSE) { // handle error here... }
步骤2:通过在调用file_get_contents()之前放置一个错误控制操作符(即@)来抑制警告:
$content = @file_get_contents($site);
eno*_*rev 134
您还可以将错误处理程序设置为匿名函数,该函数调用Exception并对该异常使用try/catch.
set_error_handler(
function ($severity, $message, $file, $line) {
throw new ErrorException($message, $severity, $severity, $file, $line);
}
);
try {
file_get_contents('www.google.com');
}
catch (Exception $e) {
echo $e->getMessage();
}
restore_error_handler();
Run Code Online (Sandbox Code Playgroud)
似乎有很多代码可以捕获一个小错误,但如果你在整个应用程序中使用异常,你只需要在顶部(例如,在一个包含的配置文件中)执行此操作,它将会将所有错误转换为异常.
Lau*_*rie 66
我最喜欢这样做的方法很简单:
if (!$data = file_get_contents("http://www.google.com")) {
$error = error_get_last();
echo "HTTP request failed. Error was: " . $error['message'];
} else {
echo "Everything went better than expected";
}
Run Code Online (Sandbox Code Playgroud)
我在使用try/catch上面的@enobrev 进行实验后发现了这一点,但这样可以减少冗长(和IMO,更易读)的代码.我们只是error_get_last用来获取最后一个错误的文本,并file_get_contents在失败时返回false,因此一个简单的"if"可以捕获它.
Ara*_*yan 20
另一种方法是抑制错误,并抛出一个稍后可以捕获的异常.如果在代码中多次调用file_get_contents(),这尤其有用,因为您不需要手动抑制和处理所有这些调用.相反,可以在单个try/catch块中对此函数进行多次调用.
// Returns the contents of a file
function file_contents($path) {
$str = @file_get_contents($path);
if ($str === FALSE) {
throw new Exception("Cannot access '$path' to read contents.");
} else {
return $str;
}
}
// Example
try {
file_contents("a");
file_contents("b");
file_contents("c");
} catch (Exception $e) {
// Deal with it.
echo "Error: " , $e->getMessage();
}
Run Code Online (Sandbox Code Playgroud)
小智 14
这是我如何做到的......不需要试试块...最好的解决方案始终是最简单的...享受!
$content = @file_get_contents("http://www.google.com");
if (strpos($http_response_header[0], "200")) {
echo "SUCCESS";
} else {
echo "FAILED";
}
Run Code Online (Sandbox Code Playgroud)
Raf*_*shi 14
function custom_file_get_contents($url) {
return file_get_contents(
$url,
false,
stream_context_create(
array(
'http' => array(
'ignore_errors' => true
)
)
)
);
}
$content=FALSE;
if($content=custom_file_get_contents($url)) {
//play with the result
} else {
//handle the error
}
Run Code Online (Sandbox Code Playgroud)
小智 6
这是我如何处理:
$this->response_body = @file_get_contents($this->url, false, $context);
if ($this->response_body === false) {
$error = error_get_last();
$error = explode(': ', $error['message']);
$error = trim($error[2]) . PHP_EOL;
fprintf(STDERR, 'Error: '. $error);
die();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
297658 次 |
| 最近记录: |