PHP HTTP Library and Error Handling

PHPHTTPLibraryandErrorHandling

Recently,IwasusingPHPcodetodosomeHTTPprotocolrequest.IhavetheTryCatchcodethere.Butitseemsitisnotworkingwell.

Ifinallyfindasolutionandfixforthebug.

Firstofall,Iamusingaobjectorientedframeworkwhichmostlyconstructbymyown.Ijustusealotofopensourcethingsandputtingtogether.

IhavesomecodeslikethisinWebHttpClient.php

<?php

namespaceJobConsumerPHP;

require__DIR__.'/../../vendor/autoload.php';

use\GuzzleHttp\Client;

use\GuzzleHttp\Psr7\Request;

use\GuzzleHttp\Exception\ConnectException;

classWebHttpClient

{

private$classifierClient=null;

private$predictionClient=null;

private$geoServerClient=null;

private$ioc=null;

publicfunction__construct($ioc)

{

$this->ioc=$ioc;

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

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

$logger->info("==============WebClientconfigstart==============");

$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{

//initclassifierHTTP

$this->classifierClient=newClient([

'base_uri'=>$classifierURL,

'timeout'=>$httpTimeout,

'connect_timeout'=>$httpTimeout,

'http_errors'=>false

]);

//initpredictionHTTP

$this->predictionClient=newClient([

'base_uri'=>$predictionURL,

'timeout'=>$httpTimeout,

'connect_timeout'=>$httpTimeout,

'headers'=>[

'Content-Type'=>'application/json',

'x-api-key'=>$predictionKey,

'api-gateway-key'=>$gatewayKey

],

'http_errors'=>false

]);

//initgeoServerHTTP

$this->geoServerClient=newClient([

'base_uri'=>$geoServerURL,

'timeout'=>$httpTimeout,

'connect_timeout'=>$httpTimeout,

'http_errors'=>false

]);

}catch(\Exception$e){

$logger->error("Couldn'tinittheHTTPClient.");

$logger->error($e->getMessage());

}

}

Firstofall,Ihaveanamespacethere,soIshouldalwaysuse\Exception,ifIonlyputExceptionthere.ThesystemcannotcatchtheExceptions.Andthehttp_errors=>falseisalsoimportant.

IftheHTTPmethodfail,thesystemneedtoretrythat.SoIhavesomecodeslikethis

/**

*retrymanytimes

*

*@paramfunction$f

*@paramnumber$delay

*@paramnumber$retryies

*/

publicfunctionretry($f,$delay=10,$retryies=3)

{

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

try{

return$f();

}catch(\Exception$e){

if($retryies>0){

$logger->error("errorhappened".$e->getMessage()."systemisretryingafter".$delay."seconds"."withthe".$retryies);

sleep($delay);

return$this->retry($f,$delay,$retryies-1);

}else{

$logger->error($e->getMessage());

}

}

}

Howweusetheretryfunctionislikethis>

publicfunctiongetFromClassifier($path)

{

return$this->ioc->retry(function()use($path){

$response=$this->classifierClient->request('GET',$path,array(

'http_errors'=>false

));

return$response;

},10,3);

}

Ilikethissolutions.Andmaybe,weshoulduseanrandomnumberthere,systemshouldretryinrandomtime,not10secondsalways.

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

相关推荐