我最近使用Guzzle来抓取一个URL,这在没有错误的情况下工作正常.
但是,如果有例如404,那么就说
$response = $client->get('http://www.google.com/test')->send();
Run Code Online (Sandbox Code Playgroud)
手册(响应状态行)建议上面的代码然后允许我打电话
$response->isSuccessful();
Run Code Online (Sandbox Code Playgroud)
但是当收到请求时出错时send()抛出a ClientErrorResponseException.抛出的异常如下
Guzzle\Http\Exception\ClientErrorResponseException
Client error response
[status code] 404
[reason phrase] Not Found
[url] http://www.google.com/test
Run Code Online (Sandbox Code Playgroud)
因此,捕获该异常显然会阻止我的应用程序暂停,但这意味着我没有一个响应对象可以调用各种isX方法.
清楚地捕获异常isSuccessful在某种程度上给出了相同的答案,但上述手册页中的一些其他方法也将有用.
我究竟做错了什么?
您可以指定['exceptions' => FALSE]为请求选项.请参阅
https://github.com/guzzle/guzzle/blob/master/docs/clients.rst#exceptions
或者,当您捕获异常时,您仍然可以获得响应:
catch (\GuzzleHttp\Exception\ClientException $e) {
$response = $e->getResponse();
}
Run Code Online (Sandbox Code Playgroud)
http://guzzle3.readthedocs.org/http-client/client.html#exceptions
感谢以下两个人在Github上指出这一点