Database Error Handling |
Can I get an example of how you would handle an error...such as if the database table doesn't exist or a field is named wrong? Currently it throws a huge full page error. Just wondering how to see that there is an error and handle it on my own.
couple of things to mention if in your index.php inside public you have
$_SERVER['CI_ENVIRONMENT'] = 'development'; you will get loads of info on error. if you change that to: $_SERVER['CI_ENVIRONMENT'] = 'production '; its a different kettle of fish. There are different ways to handle possible errors ;but really wrong field or wrong table shouldn't be one of them since you are pretty much forced to get it right when you create a model. eg protected $table = 'portfolio'; protected $primaryKey = 'Id'; protected $allowedFields = ['image','imageTitle','slug']; there are things that have crossed my mind though such as when there are no records in database i've got around this in controller with tests such as : $handle= new PortfolioModel(); $mycount= $handle->count(); if($mycount == 0) { //do something } but if i deliberately spelt a field wrong eg for table in my model, then in a controller basic block try catch works try { $handle= new PortfolioModel(); $mycount= $handle->count(); } catch ( \Exception $e) var_dump($mycount); echo $e->getMessage(); { //here i got null } the level of output depends on whether you have development or production in index.php for above when index.php has in production mode output is just one line : NULL SQLite3::query(): Unable to prepare statement: 1, no such table: portfoliol
Ya, problem is that I have a specific unusual case where the user can actually specify the sql query via an admin (admin for developers only). So if they get the query wrong, I don't want it giving a bunch of errors or a blank response Error 500. Also, I'm using custom models that aren't the standard table reflected type. Meaning, I'm running custom queries and such.
In that model or controller, the try/catch doesn't work.
> In that model or controller, the try/catch doesn't work.
Are you sure you are catching the right thing? Exceptions must be fully-qualified when you catch them from a namespace. You could try: try { $db->query($sql); } catch (\Throwable $e) { ... Notice the preceding \ on the class to catch.
Awesome! That was it! Thank you so much.
Why the backslash? What does that do?
\Throwable will load PHP built in class named Throwable. If we just specify Throwable it will try to load it within CodeIgniter.
If you execute it in a Controller, it will try to find \App\Controller\Throwable instead, and give you an error.
|
Welcome Guest, Not a member yet? Register Sign In |