Catch query exceptions in controller

Hello,

My problem is as follows. I need to catch the exception on query in controller. Query depends on user input, so It is possible(and probable) that many times user will generate error. I want to handle it in my own way.

I tried this:

https://pastebin.com/tE58S8RH

I searched whole internet, but nothing helped. Tried \PDOException etc., and still nothing. CakePHP 3.4.3 (PHP 5)

Your code seems to be valid for me.
Do you get some error message when the exception should be certainly thrown?

I get 500 error page. In development mode:

“Database Error
PDOException”

It’s like Cake handles this exception before me.

Without seeing the full stack trace I would gess that you have a problem connection to the database, that is why you get this error message as connection faliure happens before your query, so your query is not reached at all, so it can not catch the exception.

Connection seems to be good - it works fine everywhere else. If data from the the $str is correct, there is no error too. This happens only when query is invalid. Maybe attached will provide some more info.

s1

What is in your Template/Stars/search.ctp line 51? There you need a try catch block

Its: <?php if( isset($q) && $q->count() > 0 ): ?>

Good point. Seems like the problem is that $q is lazy loaded and exception happens in Template, not Controller. How can I force the query to happen in Controller? (I guess Template is no good place for try/catch).

Call $q->all() in the controller before you use set()