try/catch 无法处理异常
Can't handle exception with try/catch
我正在使用 Goutte (which uses Guzzle) 提取内容,但我的脚本以错误结尾,尽管我在 try/catch:
中 运行
Error: Client error: `GET http://example.com/C42C9CA3` resulted in a `403 Forbidden` response:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"htt (truncated...)
这是我的:
use Goutte\Client;
$HTTPconfig = [ "curl" => [
CURLOPT_TIMEOUT => 60,
CURLOPT_CONNECTTIMEOUT => 60,
CURLOPT_SSL_VERIFYPEER => false,
],
['http_errors' => false]
];
$HTTPclient = new \Goutte\Client;
$HTTPclient->setClient(new \GuzzleHttp\Client($HTTPconfig));
$HTTPclient->setHeader('user-agent', 'Mozilla/5.0 (Windows NT 6.2; rv:20.0) Gecko/20121202 Firefox/20.0');
try {
$crawler = $HTTPclient->request('GET', $url);
$doc = $crawler->html();
} catch (Exception $e) {
write($e->getMessage());
continue;
}
删除 ['http_errors' => false]
选项。默认为 true
,结果为 4xx/5xx 响应代码除外。
试试:
} catch (\Exception $e) {
而不是:
} catch (Exception $e) {
编辑:
如果您使用的是 PHP-7,您可以尝试使用斜杠来捕捉 Throwable,如下所示:
} catch (\Throwable $e) {
希望对您有所帮助
我正在使用 Goutte (which uses Guzzle) 提取内容,但我的脚本以错误结尾,尽管我在 try/catch:
中 运行Error: Client error: `GET http://example.com/C42C9CA3` resulted in a `403 Forbidden` response:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"htt (truncated...)
这是我的:
use Goutte\Client;
$HTTPconfig = [ "curl" => [
CURLOPT_TIMEOUT => 60,
CURLOPT_CONNECTTIMEOUT => 60,
CURLOPT_SSL_VERIFYPEER => false,
],
['http_errors' => false]
];
$HTTPclient = new \Goutte\Client;
$HTTPclient->setClient(new \GuzzleHttp\Client($HTTPconfig));
$HTTPclient->setHeader('user-agent', 'Mozilla/5.0 (Windows NT 6.2; rv:20.0) Gecko/20121202 Firefox/20.0');
try {
$crawler = $HTTPclient->request('GET', $url);
$doc = $crawler->html();
} catch (Exception $e) {
write($e->getMessage());
continue;
}
删除 ['http_errors' => false]
选项。默认为 true
,结果为 4xx/5xx 响应代码除外。
试试:
} catch (\Exception $e) {
而不是:
} catch (Exception $e) {
编辑:
如果您使用的是 PHP-7,您可以尝试使用斜杠来捕捉 Throwable,如下所示:
} catch (\Throwable $e) {
希望对您有所帮助