Welcome Guest, Not a member yet? Register   Sign In
Try Catch exception on MS SQL database transactions
#1

Working off of this section of the documents:
https://codeigniter.com/user_guide/datab...exceptions

In a try catch, it should catch the error and bubble it up to the calling function.  We have this code:

Model:
PHP Code:
public function insertWithException(array $data)
    {
        $insert_result false;

        $db_config_obj config('Database');
        $db_config = (array) $db_config_obj;

        // DBDebug in the Database Config must be true.
        if($db_config[$this->DBGroup]['DBDebug'])
        {
            // Retrieve the builder
            $builder $this->builder();

            // Remove the unnecessary fields from the entity,
            // using the allowFields array
            $cleaned_data $this->doProtectFields($data);

            $builder->set($cleaned_data);
            $sql $builder->getCompiledInsert();

            try
            {
                $this->db->transException(true);
                $this->db->transStart();
                $this->db->query($sql);
                $this->db->transComplete();
            }
            catch (\Exception $e)
            {
                // Automatically rolled back already.
                // Pass the exception up to the controller
                throw $e;
            }
        }
        return $insert_result;
    

And this calling function:
PHP Code:
try
        {
            $fM->insertWithException($firedrillEntity->toArray());
        }
        catch (\Exception $e)
        {
            echo "Insert failed. <br>";
            echo "Error: " $e->getMessage(); // Display the error message
        

However, the code failed on the $this->db->query($sql); line when it should have bubbled up.

Our fix is this:

Model:
PHP Code:
try
            {
                $this->db->transException(true);
                $this->db->transStart();
                $this->db->query($sql);
                $this->db->transComplete();
            }
            catch (\Throwable $e)
            {
                // Automatically rolled back already.
                // Pass the exception up to the controller
                throw $e;
            

Calling function:
PHP Code:
try
        {
            $fM->insertWithException($firedrillEntity->toArray());
        }
        catch (\Exception $e)
        {
            echo "Insert failed. <br>";
            echo "Error: " $e->getMessage(); // Display the error message
        }
        catch (\Throwable $e)
        {
            echo "Insert failed. <br>";
            echo "Error: " $e->getMessage(); // Display the error message for other types of errors
        

This works, so we're happy with it, however, is there something we missed that would have worked per the documentation?
Reply




Theme © iAndrew 2016 - Forum software by © MyBB