0

I am little confused with try catch concepts. I have this code in PHP.

<?php
while (true) {
    try {
        foreach ($data as $message) {
            $functionToCall = new functions();
            $functionToCall->remove($data);
        }
    } catch (Exception $e) {
        echo "This is inside catch";
        echo 'Message: ' . $e->getMessage();
    }
}

class functions
{
    public function __construct()
    {
        $this->dbConnection = pg_pconnect("host = $hostname port=$port dbname = $database user = $username password = $password") 
                    or die("Can't connect to database" . pg_last_error());
    }

    public function remove($data)
    {
        $query = "UPDATE table
        SET  isDeleted = true;
        $res = pg_query($this->dbConnection, $query);
        if (!$res) {
            print_r(error_get_last());
            throw new Exception(error_get_last(), 1);
        }
    }

}

I made a slight change with code to throw an exception I added

unset($this->dbconnection);

after

 $query = "UPDATE table
    SET  isDeleted = true;

to throw an exception. Exception is thrown but My catch is not catching this exception. How can I catch this error? Thanks

Unknown
  • 373
  • 1
  • 4
  • 15

1 Answers1

0

Looks like a syntax issue if that's the actual code, try this edit:

public function remove($data)
    {
        $query = "UPDATE table SET 'isDeleted'= true";
        $res = pg_query($this->dbConnection, $query);
        if (!$res) {
            print_r(error_get_last());
            throw new Exception(error_get_last(), 1);
        }
    }

Notice the quote mark changes around: $query = "UPDATE table SET 'isDeleted'= true";

Your exception logic was being parsed as a string it seems.

Notice your code doesn't close the string on $query ...

 $query = "UPDATE table
        SET  \"isDeleted\" = true;
        $res = pg_query($this->dbConnection, $query);
        if (!$res) {
            print_r(error_get_last());
            throw new Exception(error_get_last(), 1);
        }
Adam
  • 1,294
  • 11
  • 24