In a Laravel project I need to call API REST to delete remote data.
My problem is that my catch statement dont catch Guzzle exception when I got an error. My code is the following :
try {
$client = new \GuzzleHttp\Client();
$request = $client->delete(Config::get('REST_API').'/order-product/'.$id);
$status = $request->getStatusCode();
} catch (Exception $e) {
var_dump($e);exit();
}
The exception is catched by Laravel but not in my catch statement. The exception throwed by Guzzle is :
GuzzleHttp\Ring\Exception\ConnectException
It raised in my line 3 of script and it doesn't catched in my script. Could you give me a way to catch the Guzzle Exception ?
I should indicate that I already seen these posts but I not get a good response :
How to resolve cURL Error (7): couldn't connect to host?
and
Catching cURL errors from Guzzle
It worked with me when I used
\GuzzleHttp\Exception\ConnectException
instead of
\Guzzle\Http\Exception\ConnectException
I had a similar problem and solved it using the following thing.I have used your example and given the inline comments for you to understand.
try {
$client = new \GuzzleHttp\Client();
$request = $client->delete(Config::get('REST_API').'/order-product/'.$id);
$status = $request->getStatusCode();
if($status == 200){
$response = $response->json();
}else{
// The server responded with some error. You can throw back your exception
// to the calling function or decide to handle it here
throw new \Exception('Failed');
}
} catch (\Guzzle\Http\Exception\ConnectException $e) {
//Catch the guzzle connection errors over here.These errors are something
// like the connection failed or some other network error
$response = json_encode((string)$e->getResponse()->getBody());
}
Hope this helps!
Maybe that exception is not extending the Exception class. You may try to catch it like:
try {
$client = new \GuzzleHttp\Client();
$request = $client->delete(Config::get('REST_API').'/order-product/'.$id);
$status = $request->getStatusCode();
} catch (\GuzzleHttp\Ring\Exception\ConnectException $e) {
var_dump($e);exit();
} catch (Exception $e) {
// ...
}
You probably mean to catch \Exception (in the root namespace), either by adding the backslash in the catch statement or a use Exception statement.
Just Updating the answer to the new Guzzle exception namespace
try {
$client = new \GuzzleHttp\Client();
$request = $client->delete(Config::get('REST_API').'/order-product/'.$id);
$status = $request->getStatusCode();
} catch (\GuzzleHttp\Exception\ConnectException $e) {
var_dump($e);exit();
}
Related
I'm trying to customize error messages.
For handling errors i used "try/catch" block according to this Recurly documentation, like this for example:
try {
$account = Recurly_Account::get('my_account_id');
$subscription = new Recurly_Subscription();
$subscription->account = $account;
$subscription->plan_code = 'my_plan_code';
$subscription->coupon_code = 'my_coupon_code';
/* .. etc .. */
$subscription->create();
}
catch (Exception $e) {
$errorMsg = $e->getMessage();
print $errorMsg;
}
I wanted use code in catch block like this:
catch (Exception $e) {
$errorCode = $e->getCode();
print $myErrorMsg[$errorCode]; // array of my custom messages.
}
But getCode() method always returns zero for all possible errors.
My question for Recurly Team (or who there in this theme):
How i get error code for errors? Or please explain me how i can resolve this topic. Thanks!
If you look at the PHP Client on Github and you search for "throw new" which is what is done when an exception is thrown you'll see that they don't set the exception error code the second parameter of the exception constructor method.
Recurly PHP Client on Github: https://github.com/recurly/recurly-client-php/search?utf8=%E2%9C%93&q=throw+new
PHP Exception documentation: http://php.net/manual/en/language.exceptions.extending.php
Therefore, you'll either need to catch more exceptions based on their name
i.e.
catch (Recurly_NotFoundError $e) {
print 'Record could not be found';
}
OR
look at the exception message and compare it
catch (Exception $e) {
$errorMessage = $e->getMessage();
if($errorMessage=='Coupon is not redeemable.')
{
$myerrorCode=1;
}
//Add more else if, or case switch statement to handle the various errors you want to handle
print $myErrorMsg[$myerrorCode]; // array of my custom messages.
}
I have code like this:
try {
$providerError = false;
$providerErrorMessage = null;
$nbg_xml_url = "http://www.somesite.com/rss.php";
$xml_content = file_get_contents($nbg_xml_url);
// ... some code stuff
} catch (Exception $e) {
$providerError = true;
$providerErrorMessage = $e -> getMessage();
$usd = 1;
$rate = null;
$gel = null;
} finally {
// .. Write in db
}`
and problem is that, when file_get_contents can not read url (may be site not responding or something like this..) my code writes error: failed to open stream: HTTP request failed! and execution goes direct to finally block bypass catch block without entering in it..
any ideas?
You can set an empty error handler to prevent the warning and afterward throw a custom exception in case of failure. In this case I would write a custom file_get_content like so:
function get_file_contents($url) {
$xml_content = file_get_contents($url);
if(!$xml_content) {
throw new Exception('file_get_contents failed');
}
return $xml_content;
}
and would use it in your block:
set_error_handler(function() { /* ignore errors */ });
try {
$providerError = false;
$providerErrorMessage = null;
$nbg_xml_url = "http://www.somesite.com/rss.php";
$xml_content = get_file_contents($nbg_xml_url); //<----------
// ... some code stuff
} catch (Exception $e) {
$providerError = true;
$providerErrorMessage = $e -> getMessage();
$usd = 1;
$rate = null;
$gel = null;
} finally {
// .. Write in db
}
Then remember to restore the error handler calling:
restore_error_handler();
Note that when using your own error handler it will bypass the
error_reporting
setting and all errors included notices, warnings, etc., will be passed to it.
$xml_content = file_get_contents($nbg_xml_url);
The function file_get_contents does not throw an exception. Thus an exception will not be thrown if as you say the file is not found.
From the docs:
An E_WARNING level error is generated if filename cannot be found...
This function returns the read data or FALSE on failure. So you could check if $xml_content is FALSE ($xml_content === false) and proceed accordingly.
This is a php code for catching any error or exception.
Throwable is the base interface for any object that can be thrown via a throw statement, including Error and Exception.
This will catch fatal errors too. Without throwable it will not catch fatal errors.
try {
// Code that may throw an Exception or Error.
} catch (Throwable $t) {
// Executed only in PHP 7, will not match in PHP 5.x
} catch (Exception $e) {
// Executed only in PHP 5.x, will not be reached in PHP 7
}
I am using kohana 3.2 and kohana-error module is working fine, when the page does not exist.
But I have this situation: the page exist, but no data is coming, because the data does not exist. I am using the route param to check de database.
So I did this,
if($response )
{
return $response;
} else {
throw new HTTP_Exception_404('Page Not Found');
}
If there are data return, if not, create a ‘Page Not Found’ and I supose it will be caught by the kohana-error module but it is not....
Is that possible? Is this the right approach?
In your index.php, you do the following:
$request = Request::factory();
try
{
$response = $request->execute();
if (!$response->body())
{
throw new HTTP_Exception_404();
}
}
catch (Exception $exc)
{
if ($exc instanceof HTTP_Exception_404)
{
$response = Request::factory('your/404error/controller')->execute();
}
else
{
// rethrow exception
throw $exc;
}
}
echo
$response
->send_headers()
->body();
That way, you can execute a controller for each HTTP exception, or you can use a catch all 404 page for all exceptions (50x and 40x errors)
In case a request cannot be made, how can I catch the exception?
I have so far written this, but not had any luck.
$url = 'http://localhost:49000/';
//create the httprequest object
try{
$httpRequest_OBJ = new httpRequest($url, HTTP_METH_POST, $options);
}catch(HttpException $e){
echo $e;
}
I had the same problem, you should make sure that the exception is in the namespace.
What I've done is:
try {
//Request here
} catch (\HttpException $e) {
//Handle exception
} catch (\Exception $e) {
//Just in case
}
Also good to notice what is pointed in this article http://www.mkfoster.com/2009/01/06/how-to-pecl-http-request-exception-and-error-handling/ about the inner exception, in case you want the message returned by the exception.
Also, there is a php.ini directive that forces HttpRequest to always throw exception http://br.php.net/manual/en/http.configuration.php http.only_exceptions=1
how can I catch the exception?
To catch an exception you need to know the classname of the exception. What is the classname of the exception you'd like to catch?
Which of the following is better to catch an error when calling a web service using SoapClent?
try {
$response = $client->SomeSoapRequest();
}
catch(SoapFault $e){
}
Or:
try {
$response = $client->SomeSoapRequest();
}
catch(SoapFault $e){
}
catch(Exception $e){
}
Also, I want to catch a socket timeout; will this be a SoapFault or an Exception?
Thanks!
Just catch Exception; this will also catch SoapFault. If you need to know the difference, you can check the type of the object received. Exception will also catch other non-soapfault exceptions, which you should be doing anyway. So, the answer is: the second one.
you can find some answers at this similar question.