`
sillycat
  • 浏览: 2542951 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

PHP HTTP Library and Error Handling

    博客分类:
  • PHP
 
阅读更多
PHP HTTP Library and Error Handling

Recently, I was using PHP code to do some HTTP protocol request. I have the Try Catch code there. But it seems it is not working well.

I finally find a solution and fix for the bug.

First of all, I am using a object oriented framework which mostly construct by my own. I just use a lot of open source things and putting together.

I have some codes like this in WebHttpClient.php

<?php
namespace JobConsumerPHP;

require __DIR__ . '/../../vendor/autoload.php';

use \GuzzleHttp\Client;
use \GuzzleHttp\Psr7\Request;
use \GuzzleHttp\Exception\ConnectException;

class WebHttpClient
{

    private $classifierClient = null;

    private $predictionClient = null;

    private $geoServerClient = null;

    private $ioc = null;

    public function __construct($ioc)
    {
        $this->ioc = $ioc;

        $logger = $this->ioc->getService("logger");
        $config = $this->ioc->getService("config");

        $logger->info("==============WebClient config start ==============");
        $classifierURL = $config['classifierURL'];
        $classifierKey = $config['classifierKey'];

        $predictionURL = $config['predictionURL'];
        $predictionKey = $config['predictionKey'];

        $geoServerURL = $config['geoServerURL'];

        $gatewayKey = $config['gatewayKey'];
        $httpTimeout = $config['httpTimeout'];

        $logger->info("classifierURL = {$classifierURL}");
        $logger->info("classifierKey = {$classifierKey}");
        $logger->info("predictionURL = {$predictionURL}");
        $logger->info("predictionKey = {$predictionKey}");
        $logger->info("predictionKey = {$predictionKey}");
        $logger->info("httpTimeout = {$httpTimeout}");
        $logger->info("=============================================");

        try {
            // init classifier HTTP
            $this->classifierClient = new Client([
                'base_uri' => $classifierURL,
                'timeout' => $httpTimeout,
                'connect_timeout' => $httpTimeout,
                'http_errors' => false
            ]);

            // init prediction HTTP
            $this->predictionClient = new Client([
                'base_uri' => $predictionURL,
                'timeout' => $httpTimeout,
                'connect_timeout' => $httpTimeout,
                'headers' => [
                    'Content-Type' => 'application/json',
                    'x-api-key' => $predictionKey,
                    'api-gateway-key' => $gatewayKey
                ],
                'http_errors' => false
            ]);

            // init geo Server HTTP
            $this->geoServerClient = new Client([
                'base_uri' => $geoServerURL,
                'timeout' => $httpTimeout,
                'connect_timeout' => $httpTimeout,
                'http_errors' => false
            ]);
        } catch (\Exception $e) {
            $logger->error("Couldn't init the HTTP Client.");
            $logger->error($e->getMessage());
        }
    }

First of all, I have a namespace there, so I should always use \Exception, if I only put Exception there. The system can not catch the Exceptions. And the http_errors => false is also important.

If the HTTP method fail, the system need to retry that. So I have some codes like this
    /**
     * retry many times
     *
     * @param function $f
     * @param number $delay
     * @param number $retryies
     */
    public function retry($f, $delay = 10, $retryies = 3)
    {
        $logger = $this->getService("logger");

        try {
            return $f();
        } catch (\Exception $e) {
            if ($retryies > 0) {
                $logger->error("error happened " . $e->getMessage() . " system is retrying after " . $delay . " seconds" . " with the " . $retryies );
                sleep($delay);
                return $this->retry($f, $delay, $retryies - 1);
            } else {
                $logger->error($e->getMessage());
            }
        }
    }

How we use the retry function is like this>
    public function getFromClassifier($path)
    {
        return $this->ioc->retry(function () use ($path) {
            $response = $this->classifierClient->request('GET', $path , array(
                'http_errors' => false
            ));
            return $response;
        }, 10, 3);
    }

I like this solutions. And maybe, we should use an random number there, system should retry in random time, not 10 seconds always.

References:
http://stackoverflow.com/questions/32252420/guzzle-curl-error-not-catche-by-try-catch-statement-laravel
https://github.com/gidkom/php-openfire-restapi/issues/3
http://stackoverflow.com/questions/17658283/catching-exceptions-from-guzzle
分享到:
评论

相关推荐

    php.ini-development

    Transparent output compression using the zlib library ; Valid values for this option are 'off', 'on', or a specific buffer size ; to be used for compression (default is 4KB) ; Note:...

    Beginning PHP 5.3

    - **HTTP Requests:** Description of sending HTTP requests using PHP, including GET and POST requests. - **Consuming JSON/XML Data:** Techniques for consuming and processing JSON and XML data in PHP. -...

    兼容到php5.3以上(php5.6,php7)的Smtp类

    1. **Error Handling**:PHP 5.3引入了异常处理机制,代替了之前的错误报告方式。这意味着旧的错误处理函数如`@`操作符来抑制错误不再推荐使用,而是应该抛出和捕获异常。 2. **魔术常量**:`__FUNCTION__`, `__...

    php帮助文档,php。chm,php必备的中文手册

    Error Handling and Logging Functions XXXIII. Exif Functions XXXIV. Expect Functions XXXV. File Alteration Monitor Functions XXXVI. Forms Data Format Functions XXXVII. filePro Functions XXXVIII. ...

    PHP5 完整官方 中文教程

    Errors and Logging — Error Handling and Logging Functions Exif — Exif Functions Expect — Expect Functions fam — File Alteration Monitor Functions FDF — Forms Data Format Functions Fileinfo — ...

    php手册PHP5研究室编无乱码版本chm

    Error Handling and Logging Functions XXXII. Exif Functions XXXIII. File Alteration Monitor Functions XXXIV. filePro Functions XXXV. Filesystem 文件系统函数 XXXVI. Firebird/InterBase Functions ...

    php手册.chm,php手册

    Error Handling and Logging Functions XXXII. Exif Functions XXXIII. File Alteration Monitor Functions XXXIV. filePro Functions XXXV. Filesystem 文件系统函数 XXXVI. Firebird/InterBase Functions XXXVII....

    php中文完全开发手册

    Error Handling and Logging Functions XXVII. File Alteration Monitor Functions XXVIII. FrontBase Functions XXIX. filePro Functions XXX. 文件系统函数库 XXXI. Forms Data Format Functions XXXII. FriBiDi ...

    PHP函数参考手册大全

    Error Handling and Logging Functions XXXII. Exif Functions XXXIII. File Alteration Monitor Functions XXXIV. filePro Functions XXXV. Filesystem 文件系统函数 XXXVI. Firebird/InterBase Functions XXXVII....

    中文版PHP使用手册

    Error Handling and Logging Functions XXXII. Exif Functions XXXIII. File Alteration Monitor Functions XXXIV. filePro Functions XXXV. Filesystem 文件系统函数 XXXVI. Firebird/InterBase Functions XXXVII....

    PHP手册2007整合中文版

    Error Handling and Logging Functions XXXV. Exif Functions XXXVI. Expect Functions XXXVII. File Alteration Monitor Functions XXXVIII. Forms Data Format Functions XXXIX. Fileinfo Functions XL. filePro ...

    PHP官方手册中文版

    Error Handling and Logging Functions XXXV. Exif Functions XXXVI. Expect Functions XXXVII. File Alteration Monitor Functions XXXVIII. Forms Data Format Functions XXXIX. Fileinfo Functions XL. ...

    PHP5中文参考手册

    Errors and Logging — Error Handling and Logging Functions Exif — Exif Functions Expect — Expect Functions fam — File Alteration Monitor Functions FDF — Forms Data Format Functions Fileinfo — ...

    PHP5 开发手册 简体中文手册

    Error Handling and Logging Functions XXXIII. Exif Functions XXXIV. Expect Functions XXXV. File Alteration Monitor Functions XXXVI. Forms Data Format Functions XXXVII. filePro Functions XXXVIII. ...

    经典收藏最全php5.0查询手册

    Error Handling and Logging Functions XXXII. Exif Functions XXXIII. File Alteration Monitor Functions XXXIV. filePro Functions XXXV. Filesystem 文件系统函数 XXXVI. Firebird/InterBase Functions XXXVII....

    PHP手册(带评论版-2008-03-14).part2.rar

    Error Handling and Logging Functions XXXII. Exif Functions XXXIII. File Alteration Monitor Functions XXXIV. filePro Functions XXXV. Filesystem 文件系统函数 XXXVI. Firebird/InterBase Functions XXXVII....

    PHP手册(带评论版-2008-03-14).part1.rar

    Error Handling and Logging Functions XXXII. Exif Functions XXXIII. File Alteration Monitor Functions XXXIV. filePro Functions XXXV. Filesystem 文件系统函数 XXXVI. Firebird/InterBase Functions XXXVII....

    Professional_Linux_Programming.pdf

    Error Handling 420 Error-Handling Exceptions 421 02_776130 ftoc.qxp 2/2/07 10:13 PM Page xvi xvii Contents Optimization Techniques 422 Installing Additional PHP Software 427 Logging 427 Parameter ...

    up_1020948_google-api-php-client_3o3hp.rar

    5. **Error Handling**:理解和处理API调用可能出现的错误,如网络问题、权限错误或API限制。 6. **Pagination**:如果API返回大量数据,了解如何使用分页处理结果。 7. **Caching**:为提高性能,了解如何使用缓存...

Global site tag (gtag.js) - Google Analytics