how to handle error 500 when requesting a distant server with guzzle? - error-handling

i am requesting a webservice using :
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
try {
$client = new Client();
$response = $client->request('GET', $url); //it crashes at this line
$content = json_decode($response->getBody(), true);
}
catch (ConnectException $e) {
\Drupal::logger('amu_hal')->error('incorrect_url'.$url);
}
today the distant server return a error 500.
How can i modify my code not to crash my site when it happens?

I assume that by distant server you mean a server that takes a long time to connect. You can specify a timeout for the request.
Or perhaps the server returned error 500 and it fails during json_decode? You can check the status code returned by the request.
Or even perhaps the code is failing the line that you indicate but the exception ConnectException is not being caught? Try using Exception as a catch-all to debug this situation.
Instead of using Guzzle directly, I recommend that you use the Drupal wrapper (which uses Guzzle under the hood).
$client = Drupal::httpClient();
$request = $client->get($uri, ['connect_timeout' => 5]);
if ($request->getStatusCode() === 200) {
echo 'Connection Success';
} else {
echo sprintf('Error %d occurred', $request->getStatusCode());
}

Related

Prestashop REST API returning bad HTTP response with PHP client

This code:
try {
// creating webservice access
$webService = new PrestaShopWebservice('https://149.28.159.206/', '6DE5PU9M9SC7RZCRFF4VK3MFDVVTGRJT', false);
// call to retrieve all customers
$xml = $webService->get(['resource' => 'products']);
} catch (PrestaShopWebserviceException $ex) {
// Shows a message related to the error
echo 'Other error: <br />' . $ex->getMessage();
}
Is returning the following error:
Other error: <br />Bad HTTP response
And I have activated the key with the appropriate permissions (please see attached screenshot). Yet, it's giving this error.
May I know why, and how I can solve this?
I am using Prestashop 1.7.6.5 on Ubuntu 18.04 x64, from a vultr.com cloud instance.
Prestashop use Domain/api for webservics.
try "https://149.28.159.206/api/"

Magento Soap API 1.9 - failed to load external entity

when i tried to connect to Soap Api, i'm getting this error :
SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://www.lignedublanc.fr/index.php/api/soap/?wsdl' : failed to load external entity "https://www.lignedublanc.fr/index.php/api/soap/?wsdl
i tried with soap UI and same errors.
i tried everything on the net but nothing helped.
Maybe someone here can help me ?
<?php
ini_set('soap.wsdl_cache_enabled',0);
ini_set('soap.wsdl_cache_ttl',0);
$url = 'https://www.lignedublanc.fr/index.php/api/soap/?wsdl=1';
$MagentoAPILogin = '';
$MagentoAPIPass = '';
$context = stream_context_create([
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
]
]);
try {
echo "Connecting to : $url\n";
//$client = new SoapClient($url);
$client = new SoapClient($url, ['stream_context' => $context]);
echo $client->login($MagentoAPILogin, $MagentoAPIPass)."\n";
echo 'Login successful';
} catch (Exception $e) {
echo 'Login fail'."\n";
echo $e->getMessage()."\n";
echo $e->getTraceAsString()."\n";
}
I believe the problem is caused by the server not being able to access the API from the local machine. It is actually the .htaccess file that blocking any hosts except the development machines. Hence, it results in a 403 Forbidden error which is actually the SOAP error. For more reference, have a look:
Unable to connect to Magento SOAP API v2 due to "failed to load external entity"

Google API Client Libraries -PHP : Google Game Services occurs error (code : 500) without any message

I'm using Google API Client Libraries - PHP and using Service accounts issuing on Google API Console.
I want to get Leaderboards list but error occurs code 500 without any message.
Enabled Google Play Game Management, Google Play Game Services, Google+ API on API Console.
And, Android application using this Leaderboards proper.
What can I do resolve this problem?
request codes(PHP)
set_include_path(get_include_path().PATH_SEPARATOR.'/path/to/google-api-php-client/src');
require_once realpath(dirname(__FILE__).'/google-api-php-client/src/Google/autoload.php');
$client_email = 'myaccount#developer.gserviceaccount.com';
$private_key = file_get_contents('/path/to/my_key_file.p12');
$scopes = array(
Google_Service_Games::GAMES,
Google_Service_Games::PLUS_LOGIN
);
$client = new Google_Client();
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key
);
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
$service = new Google_Service_Games($client);
$response = $service->leaderboards->listLeaderboards();
echo json_encode($response) . "\n";
error occours
Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/games/v1/leaderboards: (500) {
"error": {
"code": 500,
"message": null
}
}
Additional, It is works simple query - like Book API, returned proper results without error...
$service = new Google_Service_Books($client);
$optParams = array('filter' => 'free-ebooks');
$results = $service->volumes->listVolumes('Korea', $optParams);
var_dump($results) ;
Let me know your any advice.
Thank you for your help. :)

How do I make better httpd down checker?

I have apache down checker script (remote server), but I think it doesn't work if httpd has a timeout issue or something similar.
For example, site was offline, but the server was online status.
Should I put timeout stuff or something else? How??
<?php
function GetServerStatus($site, $port)
{
$status = array("OFFLINE", "ONLINE");
$fp = #fsockopen($site, $port, $errno, $errstr, 2);
if (!$fp) {
return $status[0];
} else
{ return $status[1];}
}
?>
<?php
$status = GetServerStatus('xxx.xxx.xxx.xxx',80);
if($status == 'OFFLINE') {
$message = "Server is down now!!";
}
?>
I don't see how this can possibly report incorrectly. You could consider sending a GET / request and timing it out.
You could also consider closing the socket in the success case.

Codeigniter API error returning

Hi has anyone any experience using Phil Sturgeons RESTFUL libraries for codeigniter. I've decided to create a web service for our database in order to supply access to the database from multiple applications. The website is currently developed in Codeigniter therefore it was a simple solution to use the rest API libraries.
The problem I have is that I am trying to return specific errors in the event of a problem.
At the moment I am purposely returning an error like so:
require(APPPATH . 'libraries/REST_Controller.php');
class Settings_api extends REST_Controller {
function settings_get()
{
$this->response(NULL, 404);
}
}
If I access the url directly then I am just receiving a blank page, I can return a message if I replace the 'NULL' with a message but there is nothing to say its a 404 error whereas If I call the page via php using the following
$user = json_decode(file_get_contents('http://www.example.co.uk/api/settings_api/settings/'));
echo $user;
then it shows the following line
Message: file_get_contents(http://www.example.co.uk/api/settings_api/settings/) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 404
In both instances I would like to return a 404 error along with a message I provide. Is this possible and if so could you point me in the right direction.
Thanks
The error message being generated by PHP, as far as I know, there's nothing you can do about this (other than using the # operator, which I do NOT recommend). So, your only option is to manually check file_get_content()'s return value:
$response = file_get_contents('http://...');
if ($response === false) {
// return whatever you feel is appropriate
} else {
$user = json_decode($response);
echo $user;
}
EDIT
Found this answer here on Stackoverflow which is what you are looking for.