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?
Related
Here is my code:
try {
if ( condition 1 ) {
throw;
} else {
// do something
}
// some code here
if ( condition 2 ){
throw;
}
} catch (Exception $e) {
echo "something is wrong";
}
As you see, my catch block has its own error message, And that message is a constant. So really I don't need to pass a message when I use throw like this:
throw new Exception('error message');
Well can I use throw without anything? I just need to jump into catch block.
Honestly writing an useless error message is annoying for me.
As you know my current code has a syntax error: (it referring to throw;)
Parse error: syntax error, unexpected ';' in {path}
message parameter is optional in the Exception constructor. So if you don't have/want to put - just don't:
throw new Exception;
But you still must throw an instance of the Exception class (or a class that extends it), since it is a part of the php language syntax.
If you want all your exceptions to have the same message, you can extend it and define the message in your class:
class AmbiguousException extends Exception {
public function __construct($message = 'Something is wrong.', $code = 0, Exception $previous = null) {
parent::__construct($message, $code, $previous);
}
}
Then:
throw new AmbiguousException();
You can use the below throw everytime you need.
throw new Exception();
and catch will remain same as your code.
As stated in the PHP manual:
The thrown object must be an instance of the Exception class or a subclass of Exception. Trying to throw an object that is not will result in a PHP Fatal Error.
You can throw an exception without any message:
throw new Exception();
Perhaps something to help you from duplicating the same exception is as follows:
$e = new Exception('something is wrong');
try {
throw $e;
} catch (Exception $ex) {
echo $ex->getMessage();
}
You can create an instance with default message and then throw that instance.
$Exception = new Exception("some error message!");
try {
throw $Exception;
} catch (Exception $ex) {
var_dump($ex);
}
You cannot use the throw keyword on its own. However, you can use throw new Exception(); without specify the $message parameter, because it'll just fallback to the default message. Check out the Exceptions section in the PHP manual: http://php.net/manual/en/language.exceptions.extending.php
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();
}
I wonder if it's posible to get all the exceptions throwed.
public function test()
{
$arrayExceptions = array();
try {
throw new Exception('Division by zero.');
throw new Exception('This will never get throwed');
}
catch (Exception $e)
{
$arrayExceptions[] = $e;
}
}
I have a huge try catch block but i want to know all the errors, not only the first throwed. Is this possible with maybe more than one try or something like that or i am doing it wrong?
Thank you
You wrote it yourself: "This will never get throwed" [sic].
Because the exception will never get thrown, you cannot catch it. There only is one exception because after one exception is thrown, the whole block is abandoned and no further code in it is executed. Hence no second exception.
Maybe this was what the OP was actually asking for. If the function is not atomic and allows for some level of fault tolerance, then you can know all the errors that occurred afterwards instead of die()ing if you do something like this:
public function test()
{
$arrayExceptions = array();
try {
//action 1 throws an exception, as simulated below
throw new Exception('Division by zero.');
}
catch (Exception $e)
{
//handle action 1 's error using a default or fallback value
$arrayExceptions[] = $e;
}
try {
//action 2 throws another exception, as simulated below
throw new Exception('Value is not 42!');
}
catch (Exception $e)
{
//handle action 2 's error using a default or fallback value
$arrayExceptions[] = $e;
}
echo 'Task ended. Errors: '; // all the occurred exceptions are in the array
(count($arrayExceptions)!=0) ? print_r($arrayExceptions) : echo 'no error.';
}
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.
I been searching for this and I just seem to run into the same articles, in this code:
try
{
//some code
}
catch(Exception $e){
throw $e;
}
Where does $e gets stored or how the webmaster see it? Should I look for a special function?
An Exception object (in this case, $e) thrown from inside a catch{} block will be caught by the next highest try{} catch{} block.
Here's a silly example:
try {
try {
throw new Exception("This is thrown from the inner exception handler.");
}catch(Exception $e) {
throw $e;
}
}catch(Exception $e) {
die("I'm the outer exception handler (" . $e->getMessage() . ")<br />");
}
The output of the above is
I'm the outer exception handler (This is thrown from the inner exception handler.)
One nice thing is that Exception implements __toString() and outputs a call stack trace.
So sometimes in low-level Exceptions that I know I'm gonna want to see how I got to, in the catch() I simply do
error_log($e);
$e is an instance of Exception or any other class that extended from Exception. Those objects have some specific attributes and methods in common (inherited from the Exception class) you can use. See the chapter about exceptions and the Exception member list for more details.
I'm assuming your using some sort of third party code/library with this code in it that is throwing the exception into your code. You simply have to be ready for an exception to be thrown to catch it, then you can log it/display it however you want.
try {
$Library->procedure();
catch(Exception $e) {
echo $e->getMessage(); //would echo the exception message.
}
For more information read the PHP manual's entry on Exceptions.
The lines:
catch(Exception $e){
throw $e;
}
Don\t make sense. When you catch an Exception you're suppose to do something with the exception like:
catch(Exception $e){
error_log($e->getMessage());
die('An error has occurred');
}
But in your case the Exception is thrown directly to an outer try-block which would already happen.
If you change your code to:
//some code
Would create the exact same behaviour.