Home > Back-end >  Try/catch 'Call to a member function query() on null' error
Try/catch 'Call to a member function query() on null' error

Time:03-08

I have a SQL query ($query) that I create dynamically based on a users selections (I already perform sanitizing on user input so there is no issue of SQL injection). However sometimes the query returns a PHP Fatal error so I wanted to output all of the variables to a file so do some digging.

My code is:

try {
    $results = $db->query($query);
} catch (Exception $e) {
    $all_vars = get_defined_vars();
    file_put_contents('query_problems.txt',date('Y-m-d H:i:s') . print_r($all_vars, True),FILE_APPEND);
}

However I still receive an error

Uncaught Error: Call to a member function query() on null

and the line it points to is where I run $db->query($query).

What am I doing wrong? How do I catch this error?

CodePudding user response:

The problem is you're catching an Exception, not an Error (that is being throw). If you want to catch both (exceptions and errors), you should use Throwable.

try
{
   // Code that may throw an Exception or Error.
}
catch (Throwable $t)
{
   // Executed only in PHP 7, will not match in PHP 5
}

As it says in doc:

As the Error hierarchy does not inherit from Exception, code that uses catch (Exception $e) { ... } blocks to handle uncaught exceptions in PHP 5 will find that these Errors are not caught by these blocks. Either a catch (Error $e) { ... } block or a set_exception_handler() handler is required.

  • Related