`
sillycat
  • 浏览: 2489849 次
  • 性别: 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:...

    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. ...

    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 ...

    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手册.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 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....

    Securing PHP Web Applications.pdf

    Error Handling 13 The Guestbook Application 13 Program Summary 13 Primary Code Listing 14 From the Library of Lee Bogdanoff CONTENTS vi Users Do the Darnedest Things . . . 15 I Wonder What Will Happen...

    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. ...

    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 ...

    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....

    Joomla! 1.5 Development Cookbook.pdf

    Chapter 11: Error Handling and Reporting 279 Raising an error-level J!error 281 Raising a warning-level J!error 283 Raising a notice-level J!error 285 Enqueuing a message 287 Changing the default...

    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 ...

    ICS delphixe10源码版

    http://wiki.overbyte.be/wiki/index.php/ICS_Download ICS V5 and V6 are archive releases no longer updated, last supported release was 2007. ICS V7 is a stable release that may still be updated for ...

    WPTools.v6.29.1.Pro

    - also see FAQ: http://www.wpcubed.com/forum/viewforum.php?f=15 - and support forum: http://www.wpcubed.com/forum/ - WPTools 6 PRO and PREMIUM will be compiled as Version 5 if $define "WP6" is not set...

Global site tag (gtag.js) - Google Analytics