I'm creating a redis connection using phpredis client
$redis = new Redis();
$redis->pconnect(loclahost, 6336, 2) ;
$redis->select(15);
Now I used the $redis object inside an infinite loop.
while(true){
///using redis connection object.
}
Around 54 such individual processes were running but once or twice in a day I get an error like "read error on connection".
Please help me to fix it.
I would think something like this would work. NOTE I have not tested this, and I have not written PHP in a pretty long time.
function redisConnection() {
try {
$redis = new Redis()
$redis->pconnect(localhost, 6336, 2);
$redis->select(15);
$redis->ping();
return $redis;
} catch (Exception $e) {
throw new Exception("Can not connect: " . $e->getMessage());
}
}
$redis = redisConnection();
while (true) {
try {
$redis->ping();
} catch {
$redis = redisConnection();
}
// Rest of code
}
Related
Ive run into a little issue.
Im calling a method using the following
$this->testConnection($request->all());
The method looks like so
private function testConnection($data)
{
try {
$conn = ftp_connect($data['host']);
if (false === $conn) {
throw new Exception('Cant connect');
}
} catch (\Exception $e) {
return redirect()->route('create')->withInput()->withErrors($e->getMessage());
}
}
Update: It seems the ftp_connect PHP function isn't working and its not returning any errors
Im using Laravel 5.3
Any help would be grand.
Cheers,
The solution to this was that i was missing
use Exception;
We are using propel as orm on a mysql db.
We are changing several tables and call external services during a transaction. In between we log these actions and the response in a logging table. If an error occurs, we revert the actions but want to keep the log messages. At the moment the log messages are using the same transaction scope and would be reverted with the transaction.
Do I get a new connection and transactionscope with
$con = Propel::getConnection(DATABASE_NAME);
or do I have to check if the same connection is returned
PSEUDO CODE
public function write_log()
{
$con = Propel::getConnection(DATABASE_NAME);
$log=new Log();
$log->message('foo');
$log->save($con);
}
public function change_data()
{
write_log('start');
$con = Propel::getConnection(DATABASE_NAME);
$con->beginTransaction();
try {
//this message should stay in the database
write_log('change_db_data:'.$new_db_value);
//this should be reverted
change_db_data($new_db_value);
write_log('call webservice_1');
$response=call_webservice_1();
write_log($response);
if($response==null)
{
$con->rollback();
}
write_log('call webservice_2');
$response=call_webservice_2();
write_log($response);
if($response==null)
{
$con->rollback();
}
$con->commit();
}
catch(Exception $e){
$con->rollback();
write_log('error')
}
write_log('end');
}
Good choice picking Propel. You have two choices, either encapsulate the logging in their own transactions, or use a nested transaction, uniquely supported by Propel.
The first requires only transactionality in the write_log function:
public function write_log()
{
$con = Propel::getConnection(DATABASE_NAME);
$con->beginTransaction();
$log=new Log();
$log->message('foo');
$log->save($con);
$con->commit();
}
The second is to start a nested transaction and ensure that only the inner transaction is rolled back:
public function write_log()
{
$con = Propel::getConnection(DATABASE_NAME);
$log=new Log();
$log->message('foo');
$log->save($con);
}
public function change_data()
{
$con = Propel::getConnection(DATABASE_NAME);
$con->beginTransaction();
write_log('start');
$con->beginTransaction();
try {
//this message should stay in the database
write_log('change_db_data:'.$new_db_value);
//this should be reverted
change_db_data($new_db_value);
write_log('call webservice_1');
$response=call_webservice_1();
write_log($response);
if($response==null)
{
throw new \Exception('Null response.');
}
write_log('call webservice_2');
$response=call_webservice_2();
write_log($response);
if($response==null)
{
throw new \Exception('Null response.');
}
$con->commit();
}
catch(Exception $e){
$con->rollback();
write_log('error')
}
write_log('end');
$con->commit();
}
I am currently writing a web app in PHP and have decided to use exceptions (duh!).
I could not find an answer to whether putting try and catch blocks in all functions would be considered bad code.
I am currently using Exceptions to handle Database errors (Application errors are handled via a simple function which just adds them to an array and then they are displayed to the user). The try blocks are placed on all functions which require a database connection.
The code in question is:
public function db_conn_verify()
{
if(!isset($this->_mysqli)){
throw new Exception("Network Error: Database connection could not be established.");
} else {
return Null;
}
}
And an example function using this code:
public function get_users() {
try {
$this->db_conn_verify();
//Rest of function code
return True;
} Catch(Exception $e) {
Core::system_error('function get_users()', $e->getMessage());
return False;
}
}
Also would it be better to extend the Exception class and then use that new Exception class to handle application errors?
Thanks
I suggest to you to use something like this:
public function get_users() {
try {
if( !isset($this->_mysqli) ) {
throw new Exception("Network Error: Database connection could not be established.");
}
//Rest of function code
} Catch(Exception $e) {
Core::system_error('function get_users()', $e->getMessage());
}
}
I prefer to use my exends of Exception, but is the same. For exdending exception you can see the PHP documentation to Example #5
EDIT: For an immediate use of try-catch on database connection error you can try this:
try{
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
throw new Exception("Network Error: Database connection could not be established.");
}
} Catch(Exception $e) {
Core::system_error('function get_users()', $e->getMessage());
}
I installed redis 2.8.12 and configured phpredis. Then I called redis instance in php class. But there is no result, can you help me?
public function __construct() {
try {
echo ':) ';
$newRedis = new Redis();
echo ':P ';
}
catch (Exception $e) {
echo $e -> getMessage();
}
}
this printed :), not printed :P
Did you check if your php redis module is loaded by checking in phpinfo() ? Also, if your redis server is running properly and on which port and if configured using password you are supplying same while initiating the connection ?
You can try to use RedisException class to debug your redis connection.
try{
if( $socket = fsockopen( $host, $port, $errorNo, $errorStr )){
if( $errorNo ){
throw new RedisException(“Socket cannot be opened”);
}
}
}catch( Exception $e ){
echo $e -> getMessage( );
}
I will elaborate on the answer once you are able to give an exception or an error.
Recently I have started playing around with Exceptions and their handling. Everything seemed to work just fine however I have just hit a brick wall and I'm not sure if there is a solution for my problem or should I remake my code base.
Situation:
I'm executing a small piece of code inside try block and I'm catching all exceptions and simply logging/outputing the errors. I'm trying to execute a function which deletes object from database:
It removes the relationships;
It removes the object.
What I want to accomplish is: if object removal fails - restore previously removed relationships.
I thought that putting a nested try-catch block inside a function at the place where the final deletion is being performed I would catch an exception and revert the changes, however this does not work inside a function and it simply ignores the try-catch block and goes to the top one.
HOWEVER: When I put the same piece of code outside of the function it works just fine and like intended!
Below are two pieces of code - working and not working.
EDIT: I forgot to mention that I purposely made a syntax mistake in "router" DELETE query and it always throws an exception during "$status_r = \sys\database\query($query, $db, $elem_t, $elem);" execution. In the first case it ignores the try-catch block inside the function "delete" and goes to the top try-catch block where function is called.
NOT WORKING AS INTENDED
try
{
$db = \sys\database\connect();
$status = ips\routers\delete($id, $db);
echo "success";
\sys\core\log_action("router_delete", "success", "Router '$id' successfully deleted", $db);
}
catch (Exception $ex)
{
echo (sys\errors\is_error($ex->getMessage())) ? sys\errors\parse($ex->getMessage()) : $ex->getMessage();
\sys\core\log_action("router_delete", "failure", $ex->getMessage(), $db);
}
Code inside delete function:
function delete($id, &$db = false)
{
// Check if Any Interfaces are set on this router
if (\ips\interfaces\exists(array("router", $id), $db) !== false)
throw new \Exception(\sys\errors\exist("Router has active interfaces and cant be removed!"));
$curr_ip_id = \ips\ips\get(array("router_id", $id), "id", $db);
if (!\sys\validation\validate("numeric", $curr_ip_id[0]['id']))
throw new \Exception(\sys\errors\database());
$status = \ips\ips\revoke($curr_ip_id[0]['id'], NULL, $db);
if ($status === true)
{
// if we get an error we need to revert changes - aka rebind IP to router
try
{
$query = "DELETE FROM routers WHERE i = ?";
$elem_t = "i";
$elem = array($id);
$status_r = \sys\database\query($query, $db, $elem_t, $elem);
if ($status_r === true)
return true;
else
throw new \Exception();
}
catch (Exception $ex)
{
$status_rebind = \ips\ips\set_owner(array("id", $curr_ip_id[0]['id']), $id, "router", $db);
if ($status_rebind === true)
throw \Exception(\sys\errors\database("Failed Deleting router at the last step. IP reassigned successfully!"));
else
throw \Exception(\sys\errors\database("Failed Deleting router at the last step. IP reassigned failed!"));
}
}
else
throw new \Exception(\sys\errors\database("Failed revoking IP address from router!"));
}
WORKING AS INTENDED
try
{
$db = \sys\database\connect();
if (\ips\interfaces\exists(array("router", $id), $db) !== false)
throw new \Exception(\sys\errors\exist("Router has active interfaces and cant be removed!"));
$curr_ip_id = \ips\ips\get(array("router_id", $id), "id", $db);
if (!\sys\validation\validate("numeric", $curr_ip_id[0]['id']))
throw new \Exception(\sys\errors\database());
$status = \ips\ips\revoke($curr_ip_id[0]['id'], NULL, $db);
if ($status === true)
{
// if we get an error we need to revert changes - aka rebind IP to router
try
{
$query = "DELETE FROM routers WHERE i = ?";
$elem_t = "i";
$elem = array($id);
$status_r = \sys\database\query($query, $db, $elem_t, $elem);
if ($status_r === true)
return true;
else
throw new \Exception();
}
catch (Exception $ex)
{
$status_rebind = \ips\ips\set_owner(array("id", $curr_ip_id[0]['id']), $id, "router", $db);
if ($status_rebind === true)
throw new \Exception(\sys\errors\database("Failed Deleting router at the last step. IP reassigned successfully!"));
else
throw new \Exception(\sys\errors\database("Failed Deleting router at the last step. IP reassigned failed!"));
}
}
else
throw new \Exception(\sys\errors\database("Failed revoking IP address from router!"));
}
catch (Exception $ex)
{
echo (sys\errors\is_error($ex->getMessage())) ? sys\errors\parse($ex->getMessage()) : $ex->getMessage();
\sys\core\log_action("router_delete", "failure", $ex->getMessage(), $db);
}
I'm not exactly sure why try-catch does not work inside the function. Any help would be highly appreciated.
Thanks in advance!