[很少遇到]How to catch curl errors in PHP,怎么捕获PHP里的Curl出现的超时发生的异常错误?

jackxiang 2013-6-13 09:31 | |
背景:用try catch去捕获php的curl错误,是不行的,
The PHP cURL functions do not throw exceptions, so there will never be anything to catch. You'll just have to check the return value for a boolean false.
As to why the cURL timeout does not seem to be occurring after 30 seconds, I'm not sure.


上面代码返回:
error:Could not resolve host: 12122222.com; Host not found

打开注释代码返回:
Fatal error: Uncaught exception 'Exception' with message 'Curl Has Some Wrong ,Please Check It。' in D:\wamp\www\curl_try_catch.php on line 14
Exception: Curl Has Some Wrong ,Please Check It。 in D:\wamp\www\curl_try_catch.php on line 14
---
返回一些状态码,URl如下:curl.haxx.se/libcurl/c/libcurl-errors.html
再进行捕获。
来自:
http://stackoverflow.com/questions/3987006/how-to-catch-curl-errors-in-php

You can use the curl_error() function to know if there was some error, example:

if(curl_errno($c))
{
    echo 'error:' . curl_error($c);
}
===================================================

I'm trying to debug this cURL-operation. The var_dump() is returning bool(false)
How can I make it exit the try in that case?


Why not try throwing an Exception when false is returned?



Look here: php.net/manual/en/function.curl-exec.php; basically, false means the operation failed.
Found it: echo curl_error($ch); "Couldn't connect to host"

http://stackoverflow.com/questions/7069822/curl-try-catch-problem


群讨论:
回忆未来-向东-Jàck(372647***)  上午 10:49:40
PHP try catch 能抓到Curl的timeout吗
一周工作五天(243801***)  上午 10:50:58
不能
回忆未来-向东-Jàck(372647***)  上午 10:52:15
常规处理办法是?
三德子(277940***)  上午 10:52:31
curl没有抛异常 除非你去做个errorhandler
回忆未来-向东-Jàck(372647***)  上午 10:52:39
前一段时间我写过博文,但没有根治:http://www.jackxiang.com/post/6445/
errorhandler  ?
有示例demo么。
三德子(277940***)  上午 10:53:02
在errorhandler中 抛errorexception
看手册 errorexception这一章
回忆未来-向东-Jàck(372647***)  上午 10:53:48
嗯,超时捕获有code值没?
三德子(277940***)  上午 10:53:57

一周工作五天(243801***)  上午 10:55:41
搞那么复杂干嘛  直接把 超时时间设置长些不就ok了

----------------------------------------------------------------------------------------------
强制用try catch作下实践如下:

访问:http://jackxiang.com/test/testTimeOut
Max Time Out...time out。
Error fetching remote http://jackxiang.com/test/testMaxTimeUrl [ status 0 ]
Error fetching remote http://jackxiang.com/test/testMaxTimeUrl [ status 0 ]
Operation timed out after 5007 milliseconds with 0 bytes received
其实上述说明,不在curl里捕获,在外面一层也是能捕捉到的,只是错误的message提示是:Error:Operation timed out after 5007 milliseconds with 0 bytes received!
________________________________________________________________________________________________
在生产中的代码,用try catch实现的Remote:get,来自KO框架,作了下简单修改(有时Url为空,不知是谁调的,Add Time:2014/03/26):

作者:jackxiang@向东博客 专注WEB应用 构架之美 --- 构架之美,在于尽态极妍 | 应用之美,在于药到病除
地址:http://jackxiang.com/post/6445/
版权所有。转载时必须以链接形式注明作者和原始出处及本声明!


最后编辑: jackxiang 编辑于2014-3-26 13:54
评论列表
发表评论

昵称

网址

电邮

打开HTML 打开UBB 打开表情 隐藏 记住我 [登入] [注册]