I have a loop that checks for the existence of urls. If one does not exist Selenium exits:
XHR ERROR: URL = http://localhost/pages/156.php Response_Code = 404 Error_Message = Not Found.
If i catch the exception:
try {
$this->selenium->open($url);
}
catch(PHPUnit_Framework_Exception $e) { echo "caught\n"; }
Anything i do afterwards gives me this error:
ERROR Server Exception: sessionId should not be null; has this session been started yet?
I even tried to set the exception as expected:
$this->selenium->setExpectedException('PHPUnit_Framework_Exception');
But still the session is stopped and the test is completed. How can i make Selenium keep testing the urls? Thanks.
Create new selenium instance for every url!
$this->selenium = new Testing_Selenium("*firefox", "http://your-app-under-test.org/");
$result = $this->selenium->start();
$this->selenium->open("/the-page-to-test.php");
or see http://pear.php.net/package/Testing_Selenium/docs/0.4.3/Selenium/Testing_Selenium.html#method__construct for reference, there are more arguments to the constructor.
Related
Pretty new to laravel, so I'm not exactly sure how it handles errors and how best to catch them.
I'm using a 3rd party game server connection library that can query game servers in order to pull data such as players, current map etc..
This library is called Steam Condenser : https://github.com/koraktor/steam-condenser
I have imported this using composer in my project and all seems to be working fine, however I'm having trouble with catching exceptions that are thrown by the library.
One example is where the game server you are querying is offline.
Here is my code:
public function show($server_name)
{
try{
SteamSocket::setTimeout(3000);
$server = server::associatedServer($server_name);
$server_info = new SourceServer($server->server_ip);
$server_info->rconAuth($server->server_rcon);
$players = $server_info->getPlayers();
$total_players = count($players);
$more_info = $server_info->getServerInfo();
$maps = $server_info->rconExec('maps *');
preg_match_all("/(?<=fs\)).*?(?=\.bsp)/", $maps, $map_list);
}catch(SocketException $e){
dd("error");
}
return view('server', compact('server', 'server_info', 'total_players', 'players', 'more_info', 'map_list'));
}
If the server is offline, it will throw a SocketException, which I try to catch, however this never seems to happen. I then get the error page with the trace.
This causes a bit of a problem as I wish to simply tell the end user that the server is offline, however I cannot do this if I can't catch this error.
Is there something wrong with my try/catch? Does laravel handle catching errors in this way? Is this an issue with the 3rd party library?
A couple things:
Does the trace lead to the SocketException or to a different error? It's possible that a different error is being caught before the SocketException can be thrown.
Your catch statement is catching SocketException. Are you importing the full namespace at the top of your PHP file? use SteamCondenser\Exceptions\SocketException;
Also for debugging purposes, you could do an exception "catch all" and dump the type of exception:
try {
...
}catch(\Exception $e){
dd(get_class($e));
}
If you still get the stack trace after trying the above code, then an error is being thrown before the try/catch block starts.
I just upgraded from 4.2 to 5.0. I got all of my commands working, but I noticed in one script I see an error (an expected error) which reports ErrorException. The problem is, it breaks my script from continuing instead of moving on the the next step in a foreach loop. The same error with the same script on 4.2 will report the error and continue.
4.2: Cannot connect to xyz.IP Error 60. Operation timed out
5.0: [ErrorException]
Cannot connect to xyz.IP Error 60. Operation timed out
For more context: I'm using the script to SSH into a couple of servers and run a Ping command. I'm using Phpseclib 1.0. I've tested phpseclib on my old 4.2 build and it works fine. 5.0 is where the problem started occuring.
Does anyone know how I can make the script continue to run after an ErrorException?
foreach ($query as $key => $value) {
$ssh = new Net_SSH2($value->origin_ip);
$key = new Crypt_RSA();
$key->loadKey(decryptIt($value->password));
if (!$ssh->login($value->username, $key)) {
exit('Login Failed');
}
$this->info(' Running Ping');
//$ssh->setTimeout(1);
if ($ssh->read('/.*#.*[$|#]/', NET_SSH2_READ_REGEX)) {
//echo "reading";
//$this->info(' Running Ping');
//$ssh->setTimeout(4);
$statusOutput=$ssh->exec("ping -c 1 -W 1 ".$value->destination_ip." >/dev/null 2>&1; echo $? ");
} else {
//echo "not reading";
$this->error("Unable to Read Ping");
}
}
To work with exceptions inline within a script, use a try...catch block:
try {
$value = someFunctionThatMayCauseAnException();
} catch (Exception $e) {
$errorMessage = $e->getMessage();
}
For more information, see the PHP manual entry for Exceptions
"Uncaught" exceptions will halt your script. Sometimes, that is the desired effect. For example, the SSH library you're using does not catch the exceptions that occur within the methods, they are allowed to bubble out to the calling script. Maybe your calling script catches them, or maybe you let them keep bubbling to your global exception handler. There are a number of ways to work with exceptions, but the general rule of thumb is that you don't catch them unless you're going to do something with it, like show an error message.
Your script would continue in the previous version because the error was, most likely, emitted as a warning or notice and returning false to indicate failure. With the newer PHP version, the library began emitting exceptions instead, at once indicating failure AND providing an exception object with details about the failure.
This means you'll have to restructure the logic within your loop instead of directly calling the function in a conditional if. You didn't specify which line is emitting the exception in your example, but for instance, this is one way that you could restructure to work with exceptions:
$errorMessage = false;
try {
$ssh->login($value->username, $key); // this code is attempted
} catch (Exception $e) {
// if an exception is emitted
// in the try block above, this block
// is reached. Otherwise, it is skipped
$errorMessage = $e->getMessage();
}
// $errorMessage can only be other than false from the exception catch block above
if ($errorMessage !== false) {
exit($errorMessage);
}
Solved it. I had a try catch which I modified.
Make sure the catch has a backwards slash like this:
try {
//code here
} catch (\Exception $e) {
print_r($e->getMessage());
}
I recently migrated from age old amazon AWS SDK (v1.6.2) for PHP to the latest one. One thing I completely missed was Exception handling.
My first code.
$result = $this->S3Client->putObject($options);
if (!empty($result)) {
return !0;
}
But if upload fails, then it will throw an exception which will crash my PHP. So, I added exception handling next.
try {
$result = $this->S3Client->putObject($options);
return !0;
} catch(Exception $e) {
log_message($e->message);
return !1;
}
However, it seems that $e->message is protected.
Question: How can I get the error so that I can root cause what happened with the upload, once I move to production environment?
Try using:
log_message($e->getMessage());
More info here and here.
I'm using the amqp extension in pecl 1.0.3, compiled with 2.7.1 rabbitmq.
I'm trying to get a basic consumer/producer example working, but I keep getting errors. There's very little php documentation on this extension and a lot of it seemed to be outdated or wrong.
I used the code a user posted, but can't seem to get the consumer part working
Connection:
function amqp_connection() {
$amqpConnection = new AMQPConnection();
$amqpConnection->setLogin("guest");
$amqpConnection->setPassword("guest");
$amqpConnection->connect();
if(!$amqpConnection->isConnected()) {
die("Cannot connect to the broker, exiting !\n");
}
return $amqpConnection;
}
Sender:
function amqp_send($text, $routingKey, $exchangeName){
$amqpConnection = amqp_connection();
$channel = new AMQPChannel($amqpConnection);
$exchange = new AMQPExchange($channel);
$exchange->setName($exchangeName);
$exchange->setType("fanout");
if($message = $exchange->publish($text, $routingKey)){
echo "sent";
}
if (!$amqpConnection->disconnect()) {
throw new Exception("Could not disconnect !");
}
}
Receiver:
function amqp_receive($exchangeName, $routingKey, $queueName) {
$amqpConnection = amqp_connection();
$channel = new AMQPChannel($amqpConnection);
$queue = new AMQPQueue($channel);
$queue->setName($queueName);
$queue->bind($exchangeName, $routingKey);
//Grab the info
//...
}
Then sending it:
amqp_send("Abcdefg", "action", "amq.fanout");
And Receiving it:
amqp_receive("amq.fanout","action","action");
I keep getting a problem running the script and points to the amqp receive:
PHP Fatal error: Uncaught exception 'AMQPQueueException' with message 'Server channel error: 404, message: NOT_FOUND - no queue 'action' in vhost '/'' in /home/jamescowhen/test.php:21
Can anyone point me to the right direction? The whole sample is from a user note here:
http://www.php.net/manual/en/amqp.examples.php#109024
The exception seems to be caused by your queue not being declared (as the error message describes 404 - the queue 'action' was not found). The reason why the example works for the original poster is probably because he already has declared the queue earlier, without realizing that it's missing in his example.
You can declare the queue by calling ->declare() on the queue object. You'll also have to do this with the exchange object, unless you're certain that it already exists when you attempt to hook the queue onto it.
I am writing a web app which will allow the user to specify a URL for a SoapClient. I wanted to validate that php can connect to the client when the user submits a form. I thouhgt I could do this via try catch or set_error_handler (or some combination of the two). However it looks like this is not possible for fatal errors. Is there a way to get SoapClent to test a URL which won't throw an unrecoverable error?
Fatal error: SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://example.com/wibble'
I want it to flag an error as the URL doesn’t exist, but I would like to be able to catch it.
Otherwise I suppose I could try to download and validate the URL myself, but I would have thought that it would be possible to do it from the SoapClient.
Should this be a fatal error?
Edit
After reading rogeriopvl's answer I reaslise that I should have said that I had tried the 'exceptions' option to the soapclient constructor and (in desperation) the use-soap-error-handler function.
Are you using xdebug? According to this PHP bug report and discussion, the issue has been fixed at least since PHP 5.1, but this xdebug bug messes with 'fatal error to exception conversions' in a way that the exception is not generated and the fatal error 'leaks through'.
I can reproduce this locally, with xdebug enabled:
try {
$soapClient = new SoapClient('http://www.example.com');
}
catch(Exception $e) {
$exceptionMessage = t($e->getMessage());
print_r($exceptionMessage);
}
This gives me the fatal error you described, without even entering the catch clause:
Fatal error: SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://www.example.com'
It works if I disable xdebug right before the call:
xdebug_disable();
try {
$soapClient = new SoapClient('http://www.example.com');
}
catch(Exception $e) {
$exceptionMessage = t($e->getMessage());
print_r($exceptionMessage);
}
This triggers the exception as expected, and I get a proper SoapFault Object in the catch clause with a message of:
SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://www.example.com'
So basically exceptions work as advertised. If they don't work in your case, you might encounter the xdebug bug, or maybe a similar issue with another 3rd party component.
Quoting SoapClient documentation:
The exceptions option is a boolean value defining whether soap errors throw exceptions of type SoapFault.
So you should try something like:
$client = new SoapClient("some.wsdl", array('exceptions' => TRUE));
This way will throw SoapFault exceptions allowing you to catch them.
See: http://bugs.xdebug.org/view.php?id=249
Possible solution:
Index: trunk/www/sites/all/libraries/classes/defaqtoSoapClient.class.php
===================================================================
--- classes/defaqtoSoapClient.class.php
+++ classes/defaqtoSoapClient.class.php
## -31,10 +31,23 ##
try {
+ // xdebug and soap exception handling interfere with each other here
+ // so disable xdebug if it is on - just for this call
+ if (function_exists('xdebug_disable')) {
+ xdebug_disable();
+ }
//Create the SoapClient instance
parent::__construct($wsdl, $options);
}
catch(Exception $parent_class_construct_exception) {
+ if (function_exists('xdebug_enable')) {
+ xdebug_enable();
+ }
// Throw an exception an say that the SOAP client initialisation is failed
throw $parent_class_construct_exception;
+ }
+ if (function_exists('xdebug_enable')) {
+ xdebug_enable();
}
}
you could try and do a curl or fsockopen request to check the URL is valid.
For your information, i'm using SoapClient with PHPUnit to test remote WebServices and got the same problem!
when using an old PHPUnit version (3.3.x) as third party, phpunit crash
when using current version of PHPUnit (3.4.6) as third party, phpunit display "RuntimeException".
Here is my first test method :
public function testUnavailableURL() {
$client = new SoapClient("http://wrong.URI");
}
Here is PHPUnit first result :
There was 1 error:
1) MyTestCase::testUnavailableURL
RuntimeException:
FAILURES!
Here is my second test method :
public function testUnavailableURL() {
try {
$client = #new SoapClient("http://wrong.URI");
} catch (SoapFault $fault) {
print "SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})";
}
}
Here is PHPUnit second test result :
PHPUnit 3.4.6 by Sebastian Bergmann.
.SOAP Fault: (faultcode: WSDL, faultstring: SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://wrong.URI' : failed to load external entity "http://wrong.URI"
)...
Time: 3 seconds, Memory: 4.25Mb
OK
NB: i found a phpunit ticket on this subject : ticket 417